We will use below script to get list of all indexes along with script to enable and Rebuild indexes.
Script:
SELECT SchemaName = SCHEMA_NAME (o.SCHEMA_ID)
,ObjectName = o.name
,IndexName = i.name
, I.index_id
, i.is_disabled
, DisableIndexStatement = 'ALTER INDEX [' + i.Name + '] ON [' + SCHEMA_NAME (o.SCHEMA_ID) + '].[' + o.name + '] DISABLE'
, EnableIndexStatement = 'ALTER INDEX [' + i.Name + '] ON [' + SCHEMA_NAME (o.SCHEMA_ID) + '].[' + o.name + '] REBUILD'
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
SSIS Package:
Script:
SELECT SchemaName = SCHEMA_NAME (o.SCHEMA_ID)
,ObjectName = o.name
,IndexName = i.name
, I.index_id
, i.is_disabled
, DisableIndexStatement = 'ALTER INDEX [' + i.Name + '] ON [' + SCHEMA_NAME (o.SCHEMA_ID) + '].[' + o.name + '] DISABLE'
, EnableIndexStatement = 'ALTER INDEX [' + i.Name + '] ON [' + SCHEMA_NAME (o.SCHEMA_ID) + '].[' + o.name + '] REBUILD'
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
SSIS Package:
No comments:
Post a Comment