Saturday, 18 October 2014

SQL Query to Get List of All Non Clustered Indexes

SELECT SchemaName = SCHEMA_NAME (o.SCHEMA_ID)      
   ,ObjectName = o.name      
   ,IndexName = i.name      
   ,DropIndexStatement = 'DROP INDEX [' + i.Name + '] ON [' + SCHEMA_NAME (o.SCHEMA_ID)      
   + '].[' + o.name + ']'      
   ,CreateIndexStatement = 'CREATE ' + (CASE i.is_unique WHEN 1 THEN 'UNIQUE ' ELSE '' END)      
   + 'NONCLUSTERED INDEX ['      
   + i.name + '] ON [' + SCHEMA_NAME (o.SCHEMA_ID) + '].[' + o.name + '] ( '      
   + LEFT(list, ISNULL(splitter-1,LEN(list))) + ' ) '      
   + ISNULL('INCLUDE ( ' + SUBSTRING(list, indCol.splitter +1, 100) + ' ) ','')      
   + ISNULL('WHERE ' + i.filter_definition,'')      
FROM sys.indexes i      
JOIN sys.objects o ON i.OBJECT_ID = o.OBJECT_ID      
CROSS APPLY      
(SELECT splitter = NULLIF(CHARINDEX('|',indexCols.list),0)      
 , list      
 FROM (SELECT list=CAST((      
   SELECT CASE WHEN sc.is_included_column = 1 AND sc.ColPos = 1 THEN '|' ELSE '' END +      
     CASE WHEN sc.ColPos  > 1 THEN ', ' ELSE '' END + name +      
            CASE WHEN sc.is_descending_key=1 THEN ' DESC' ELSE '' END      
            FROM (SELECT sc.is_descending_key      
       , sc.is_included_column      
       , index_column_id      
       , name = '[' + name + ']'      
       , ColPos = ROW_NUMBER() OVER (PARTITION BY sc.is_included_column      
           ORDER BY sc.index_column_id)      
         FROM sys.index_columns  sc      
         JOIN sys.columns c ON sc.OBJECT_ID = c.OBJECT_ID      
           AND sc.column_id = c.column_id      
         WHERE sc.index_id = i.index_id      
                    AND sc.OBJECT_ID = i.OBJECT_ID ) sc      
                    ORDER BY sc.is_included_column, ColPos      
                      FOR XML PATH (''), TYPE) AS VARCHAR(MAX))      
   )indexCols      
) indCol      
WHERE i.is_primary_key=0      
AND i.is_unique_constraint=0      
AND i.type_desc=N'NONCLUSTERED'      
AND o.TYPE=N'U'      
ORDER BY SchemaName, ObjectName, IndexName


No comments:

Post a Comment