Sql – clean T-SQL query I can use to verify an index has the right columns


I am writing a DB upgrade script that will check to see if an index has the right two columns defined. If it doesn't, or if it only has one of them, then I will DROP it (is there a way to ALTER an index?) and then recreate it with both.

Best Solution

I don't have a database immediately on-hand to test this, but you should be able to see if a column exists in an index by using the following IF EXISTS statement.

I'm not sure whether you can alter an index on the fly.

   SELECT MyIndex.Name AS IndexName, 
          Columns.name AS ColumnName 
   FROM sys.indexes MyIndex
   INNER JOIN sys.index_columns IndexColumns 
      ON  MyIndex.index_id = IndexColumns.index_id
      AND MyIndex.object_id = IndexColumns.object_id 
   INNER JOIN sys.columns Columns
      ON  Columns.column_id = IndexColumns.column_id 
      AND IndexColumns.object_id = Columns.object_id 
   WHERE Columns.name = 'ColumnName'
   AND MyIndex.Name='IX_MyIndexName'