Is there a pure T-SQL query that I can use to verify that the index has the correct columns?

I am writing a DB update script that checks if a pointer has two valid two columns. If this is not the case, or if it has only one of them, then I DROP it (is there a way to ALTER the index?), And then recreate it using both.

+5
source share
2 answers

I don't have a database right away to check this out, but you should see if a column exists in the index using the following IF EXISTS statement.

I'm not sure if you can change the index on the fly.

IF EXISTS
(
   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'
)
+7
source

, . , , . . , .


IF EXISTS
(
    SELECT i.Name AS IndexName, c.Name AS ColumnName
    FROM sys.indexes i
        JOIN sys.index_columns ic
            ON i.object_id = ic.object_id AND i.index_id = ic.index_id
        JOIN sys.columns c
            ON ic.object_id = c.object_id AND c.column_id = ic.column_id
    WHERE c.Name = 'MyColumnName' AND i.Name='MyIndexName'
)

+4

All Articles