Thursday, 26 September 2013

Dynamically Drop Table Constraints


System generated constraints take on a naming convention of their own. Unfortunately the naming convention in production is rarely the same name in the uncontrolled environments. Using this script, you can dynamically drop all system generated constraints. It doesn’t go as far are re-creating them, however it’s a start.

Just change the values of the @TableSchema and TableName variables below:

DECLARE @TableName      VARCHAR(100)
DECLARE @TableSchema    VARCHAR(100)
DECLARE @CountConst     INT
DECLARE @DEFAULT        sysname
DECLARE @SQLDropMe      VARCHAR(MAX)
DECLARE @ColumnNames    VARCHAR(MAX)

SET @TableSchema = 'dbo'
SET @TableName = 'employees'

--------------------------------------------- Store Existing Column Names
SET @ColumnNames = SUBSTRING((SELECT
            ',' + r.COLUMN_NAME
            FROM(
                SELECT COLUMN_NAME
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA = @TableSchema AND
                    TABLE_NAME = @TableName
            ) r
            FOR XML PATH('')   ), 2, 8000)
--------------------------------------------- /Store Existing Column Names



--------------------------------------------- Insert contents into temp table

EXEC ('SELECT * INTO ' + @TableSchema + '.tmp01_' + @TableName + ' FROM ' + @TableSchema + '.' + @TableName)

--------------------------------------------- /Insert contents into temp table



--------------------------------------------- Drop all the constraints

DECLARE @TableConstraints TABLE
(
    ID              INT     IDENTITY(1,1)
    ,DefaultConst   sysname
)

INSERT INTO @TableConstraints
(
    DefaultConst
)
SELECT object_name(default_object_id)
FROM sys.COLUMNS
WHERE object_id = object_id(@TableSchema + '.' + @TableName)
    AND object_name(default_object_id) IS NOT NULL

SET @CountConst = (SELECT MAX(ID) FROM @TableConstraints)

WHILE @CountConst > 0
BEGIN
    SET @DEFAULT = (SELECT DefaultConst FROM @TableConstraints WHERE ID = @CountConst)
    SET @SQLDropMe = 'ALTER TABLE ' + @TableSchema + '.' + @TableName + ' DROP CONSTRAINT ' + @DEFAULT
    SELECT @SQLDropMe
    --EXEC (@SQLDropMe)
   
    SET @CountConst = @CountConst - 1
END
--------------------------------------------- /Drop all the constraints


No comments: