删除和重新创建约束脚本

时间:2018-05-02 05:35:31

标签: sql sql-server

我有一个表名Employee,它引用了数据库中的近85个表。我想在表结构中进行少量更改,为此我必须删除并重新创建表,但由于这是参考了很多表我不能删除它。我可以以某种方式获取约束的脚本以丢弃并重新创建它们,因为我也需要这些约束。我不能永远放弃它们。

我能够找到子表和约束的名称,但我想要我可以删除的脚本并重新创建约束。

SELECT name AS 'Foreign Key Constraint Name', 
           OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) AS 'Child Table'
   FROM sys.foreign_keys 
   WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'HRM' AND 
              OBJECT_NAME(referenced_object_id) = 'tbl_EmployeeInfo'

最佳

1 个答案:

答案 0 :(得分:2)

-- =========================================================================
--                              Read the comments !!!
-- =========================================================================
DECLARE
    @source_table VARCHAR(50),
    @source_constarint VARCHAR(50),
    @source_column VARCHAR(50),
    @target_table VARCHAR(50),
    @target_column VARCHAR(50),
    @drop NVARCHAR(4000)

-- Remember the keys
SELECT 
    ccu.TABLE_NAME AS source_table
    ,ccu.CONSTRAINT_NAME AS source_constraint
    ,ccu.COLUMN_NAME AS source_column
    ,kcu.TABLE_NAME AS target_table
    ,kcu.COLUMN_NAME AS target_column
INTO #keys
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
    INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
        ON ccu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME 
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu 
        ON kcu.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME 
WHERE ccu.TABLE_NAME ='TABLE NAME'

-- Delete keys
DECLARE drop_keys CURSOR FOR 
SELECT 
    source_table,
    source_constraint,
    source_column,
    target_table,
    target_column
FROM #keys
OPEN drop_keys
FETCH NEXT FROM drop_keys INTO @source_table, @source_constarint, @source_column, @target_table, @target_column
WHILE @@fetch_status <> -1
BEGIN
         SET @drop = 
         'ALTER TABLE ' + @source_table + ' DROP CONSTRAINT ' + @source_constarint 

         EXEC sp_executesql @drop

        SELECT @drop

        FETCH NEXT FROM drop_keys INTO @source_table, @source_constarint, @source_column, @target_table, @target_column
    END
    CLOSE drop_keys
    DEALLOCATE drop_keys


    -- =========================================================================
    --                      Your changes
    -- =========================================================================

    -- =========================================================================
    --                      Write a similar cursor to create keys
    --                      Make sure your cursor is creating keys
    -- =========================================================================

-- DROP table #keys -- Maybe just do not delete it until you not to recreate the keys
                    -- Maybe, Instead of inserting into a temporary table, insert it into a regular table