How can foreign key constraints be temporarily disabled using T-SQL?

后端 未结 16 1908
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop and then re-create

16条回答
  •  情歌与酒
    2020-11-22 05:26

    Find the constraint

    SELECT * 
    FROM sys.foreign_keys
    WHERE referenced_object_id = object_id('TABLE_NAME')
    

    Execute the SQL generated by this SQL

    SELECT 
        'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(parent_object_id) +
        '.[' + OBJECT_NAME(parent_object_id) + 
        '] DROP CONSTRAINT ' + name
    FROM sys.foreign_keys
    WHERE referenced_object_id = object_id('TABLE_NAME')
    

    Safeway.

    Note: Added solution for droping the constraint so that table can be dropped or modified without any constraint error.

提交回复
热议问题