/*
DROP PROCEDURE USP_GetIndexSQL
*/
-- given a table name; this SP returned remove index script in IXSQL1 and create index script in IXSQL2
CREATE PROCEDURE USP_GetIndexSQL
@TableName VARCHAR(200),
@IXSQL1 NVARCHAR(MAX) OUT,
@IXSQL2 NVARCHAR(MAX) OUT
AS
--DECLARE @IXSQL1 NVARCHAR(MAX), @IXSQL2 NVARCHAR(MAX), @TableName VARCHAR(200); SELECT @TableName = 'openinvinvoice'
-- Get all existing indexes, but NOT the primary keys
DECLARE cIX CURSOR FOR
SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID
FROM Sys.Indexes SI
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON SI.Name = TC.CONSTRAINT_NAME AND OBJECT_NAME(SI.Object_ID) = TC.TABLE_NAME
WHERE TC.CONSTRAINT_NAME IS NULL
AND OBJECTPROPERTY(SI.Object_ID, 'IsUserTable') = 1
AND OBJECT_NAME(SI.Object_ID) = @TableName
AND SI.Name IS NOT NULL
ORDER BY OBJECT_NAME(SI.Object_ID), SI.Index_ID
DECLARE @IxTable SYSNAME
DECLARE @IxTableID INT
DECLARE @IxName SYSNAME
DECLARE @IxID INT
SET @IXSQL1 = ''
SET @IXSQL2 = ''
-- Loop through all indexes
OPEN cIX FETCH NEXT FROM cIX INTO @IxTable, @IxTableID, @IxName, @IxID WHILE (@@FETCH_STATUS = 0)
BEGIN
SELECT @IXSQL1 = @IXSQL1 + 'DROP INDEX ' + @IxName + ' ON LP.' + @IxTable + ';' + CHAR(13) + CHAR(10)
SELECT @IXSQL2 = @IXSQL2 + 'CREATE '
-- Check if the index is unique
IF (INDEXPROPERTY(@IxTableID, @IxName, 'IsUnique') = 1)
SELECT @IXSQL2 = @IXSQL2 + 'UNIQUE '
-- Check if the index is clustered
IF (INDEXPROPERTY(@IxTableID, @IxName, 'IsClustered') = 1)
SELECT @IXSQL2 = @IXSQL2 + 'CLUSTERED '
SELECT @IXSQL2 = @IXSQL2 + 'INDEX ' + @IxName + ' ON LP.' + @IxTable + '('
-- Get all columns of the index
DECLARE cIxColumn CURSOR FOR
SELECT SC.Name
FROM Sys.Index_Columns IC
JOIN Sys.Columns SC ON IC.Object_ID = SC.Object_ID AND IC.Column_ID = SC.Column_ID
WHERE IC.Object_ID = @IxTableID AND Index_ID = @IxID
ORDER BY IC.Index_Column_ID
DECLARE @IxColumn SYSNAME
DECLARE @IxFirstColumn BIT SELECT @IxFirstColumn = 1
-- Loop throug all columns of the index and append them to the CREATE statement
OPEN cIxColumn FETCH NEXT FROM cIxColumn INTO @IxColumn WHILE (@@FETCH_STATUS = 0)
BEGIN
IF (@IxFirstColumn = 1)
SELECT @IxFirstColumn = 0
ELSE
SELECT @IXSQL2 = @IXSQL2 + ', '
SELECT @IXSQL2 = @IXSQL2 + @IxColumn
FETCH NEXT FROM cIxColumn INTO @IxColumn
END
CLOSE cIxColumn
DEALLOCATE cIxColumn
SELECT @IXSQL2 = @IXSQL2 + ');' + CHAR(13) + CHAR(10)
FETCH NEXT FROM cIX INTO @IxTable, @IxTableID, @IxName, @IxID
END
CLOSE cIX
DEALLOCATE cIX
GO
--SELECT @IXSQL1
--SELECT @IXSQL2
No comments:
Post a Comment