How do I drop all foreign-key constraints on a table in Sql Server 2000?

后端 未结 3 2005
孤独总比滥情好
孤独总比滥情好 2020-12-30 04:38

How do I drop all foreign-key constraints on a table in SQL Server 2000 using T-SQL?

3条回答
  •  醉话见心
    2020-12-30 05:04

    Here you go: (not tested on SQL2000, but should be ok)

    Generates 'disables':

    SELECT  'IF EXISTS (SELECT * FROM sys.foreign_keys 
       WHERE object_id = OBJECT_ID(N''[dbo].' + FK +''') 
       AND parent_object_id = OBJECT_ID(N''[dbo].' + PT + ''')) 
       ALTER TABLE ' + PT + ' NOCHECK CONSTRAINT ' + FK + ';'
    FROM 
    (SELECT 
        OBJECT_NAME(constraint_object_id) as FK,
        OBJECT_NAME(parent_object_id) as PT
        FROM [sys].[foreign_key_columns] ) T
    ORDER BY FK
    

    Generates 'enables':

    SELECT  'ALTER TABLE ' + PT + ' WITH CHECK CHECK CONSTRAINT ' + FK + ';'
    FROM 
    (SELECT 
        OBJECT_NAME(constraint_object_id) as FK,
        OBJECT_NAME(parent_object_id) as PT
        FROM [sys].[foreign_key_columns] ) T
    ORDER BY FK
    

    Update: Oops, I thought you wanted it for all tables :) You can just modify above for your single table.

提交回复
热议问题