DECLARE @T_IndexInfo TABLE
(
IndID NVARCHAR(128),
ObjectID NVARCHAR(128),
ColID NVARCHAR(128),
IndexName NVARCHAR(128),
TableName NVARCHAR(128),
ColumnName NVARCHAR(128),
KeyNo NVARCHAR(128),
ColType NVARCHAR(128)
)
INSERT INTO @T_IndexInfo
SELECT I.IndID,
SO.ID AS 'ObjectID',
SK.ColID,
I.Name AS 'IndexName',
SO.Name AS 'TableName',
SC.Name AS 'ColumnName',
Sk.KeyNo,
CASE WHEN Sk.KeyNo = 0 THEN 'Include'
ELSE 'Normal'
END AS 'ColType'
FROM sys.sysindexes I
INNER JOIN sys.sysobjects SO ON SO.ID = I.ID
AND SO.xtype = 'U'
INNER JOIN sys.sysindexkeys SK ON SK.IndID = I.IndID
AND SO.ID = SK.ID
INNER JOIN sys.syscolumns SC ON SC.ID = SO.ID
AND SC.ColID = SK.ColID
WHERE I.IndID > 0
AND I.IndID < 255
AND ( I.Status & 64 ) = 0
-- AND ( I.status & 2048 ) <> 2048 /******** comment this if PK's also need to be recreated *****/
ORDER BY SO.Name,
I.Name
DECLARE @T_Final TABLE
(
TableName NVARCHAR(128),
IndexName NVARCHAR(128),
NormalColumns NVARCHAR(MAX),
IncludedColumns NVARCHAR(MAX)
)
INSERT INTO @T_Final
SELECT DISTINCT
TableName,
IndexName,
STUFF(( SELECT ',[' + ColumnName + ']'
FROM @T_IndexInfo
WHERE IndID = I.IndID
AND ObjectID = I.ObjectID
AND ColType = 'Normal'
ORDER BY KeyNo
FOR
XML PATH('')
), 1, 1, '') AS 'NormalColumns',
STUFF(( SELECT ',[' + ColumnName + ']'
FROM @T_IndexInfo
WHERE IndID = I.IndID
AND ObjectID = I.ObjectID
AND ColType = 'Include'
FOR
XML PATH('')
), 1, 1, '') AS 'IncludedColumns'
FROM @T_IndexInfo I;
WITH indexCTE AS
(
SELECT Table_Name, Column_Name --, Collation_Name
FROM information_schema.columns
WHERE Collation_Name IS NOT NULL AND Collation_Name = 'Modern_Spanish_CI_AS'
),
indexCTE2 AS
(
SELECT i.Name [Index Name], OBJECT_NAME(i.object_ID) [Table Name], c.Name [Column Name]
FROM sys.indexes i
INNER JOIN sys.index_columns ic ON i.index_id = ic.index_id AND i.object_id = ic.object_id
INNER JOIN sys.columns c ON ic.column_id = c.column_id AND ic.object_id = c.OBJECT_ID
WHERE EXISTS (SELECT 1 FROM indexCTE t1 WHERE t1.Table_Name = OBJECT_NAME(i.object_ID) AND t1.Column_Name = c.Name)
)
SELECT IndexName, TableName, NormalColumns, IncludedColumns
INTO #temp1
FROM @T_Final z INNER JOIN indexCTE2 x ON z.IndexName = x.[Index Name]
-- To generate CREATE INDEX SCRIPT
SELECT 'CREATE INDEX [' + IndexName + '] ON [' + TableName + '].('
+ NormalColumns + ')' + CASE WHEN IncludedColumns IS NULL THEN ''
ELSE ' INCLUDE (' + IncludedColumns + ')'
END AS 'CreateScript'
FROM #temp1
-- To generate DROP INDEX SCRIPT
SELECT 'DROP INDEX [' + TableName + '].[' + IndexName + ']' AS 'DropScript'
FROM #temp1
DROP TABLE #temp1