Link to home
Start Free TrialLog in
Avatar of Phil Chapman
Phil ChapmanFlag for United States of America

asked on

MSSQL 2008 R2 Check to see if a Index/Key Exist

What query could I use to see if Index/Key IX_Flag exist in table MyDataTable


Example:
SELECT FLAG
WHERE .............
--------------------
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

You can start with a simple query like this one:
SELECT T.name, I.name, *
FROM sys.indexes AS I
INNER JOIN sys.tables AS T
ON T.object_id = I.object_id
ORDER BY T.name, I.name
Avatar of Phil Chapman

ASKER

I'm getting errors could you create the query using

Field  Flag
Index  IX_Flag
Table MyDataTable

Example:
SELECT FLAG
......................
.....................
From what I read from your question, you want to check for the existence of an index named IX_Flag for a given name. Is that what you want? That query does not contains a field called Flag so it cannot be part of the SELECT statement:
SELECT T.name, I.name, * 
FROM sys.indexes AS I
INNER JOIN sys.tables AS T
ON T.object_id = I.object_id
WHERE T.name = 'MyDataTable'
AND I.name = 'IX_Flag'
ORDER BY T.name, I.name

Open in new window


Or do you want to retrieve the data of the field Flag from MyDatable? In that case that would be:
SELECT Flag
FROM MyDataTable

Open in new window

In that latest query, you should not specify the index to use.
The query  worked.  But I need it to
If the Index IX_Flag does not exist it should not return any data
if it does exist is should return something ( It could be any field )

What I need to do is run the query if it finds the IX_Flag index it should return something.  If the IX_Flag does not exist is should not return anything.
I still don't understand. To check if IX_Flag exist, you can use the first query:

SELECT T.name, I.name, * 
FROM sys.indexes AS I
INNER JOIN sys.tables AS T
ON T.object_id = I.object_id
WHERE T.name = 'MyDataTable'
AND I.name = 'IX_Flag'
ORDER BY T.name, I.name

Open in new window


Do you a matching row for that query returned here? If yes, then your index exist.
ASKER CERTIFIED SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Perfect

Thanks