Labels

Monday, January 2, 2012

indexes with column list

-- List all indexes in single row with column list
USE AdventureWorks2008; 
SELECT   DISTINCT SchemaName = schema_name(schema_id), 
         TableName = object_name(t.object_id), 
         ColumnList = Stuff((SELECT  ', ' + c1.Name AS [text()] 
                            FROM sys.indexes i1 
         INNER JOIN sys.tables t1 
           ON i1.object_id = t1.object_id 
         INNER JOIN sys.index_columns ic1 
           ON ic1.object_id = t1.object_id 
              AND ic1.index_id = i1.index_id 
         INNER JOIN sys.columns c1 
           ON c1.object_id = t1.object_id 
              AND ic1.column_id = c1.column_id 
                            WHERE t.schema_id = t1.schema_id
                                  and t.object_id = t1.object_id
                                  and i.name =i1.name
                            FOR XML PATH ('')),1,1,''), 
         IndexName = i.Name 
FROM     sys.indexes i 
         INNER JOIN sys.tables t 
           ON i.object_id = t.object_id 
         INNER JOIN sys.index_columns ic 
           ON ic.object_id = t.object_id 
              AND ic.index_id = i.index_id 
         INNER JOIN sys.columns c 
           ON c.object_id = t.object_id 
              AND ic.column_id = c.column_id 
ORDER BY SchemaName, 
         TableName, 
         IndexName

No comments:

Post a Comment