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

后端 未结 16 2302
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:27

    If you want to disable all constraints in the database just run this code:

    -- disable all constraints
    EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    

    To switch them back on, run: (the print is optional of course and it is just listing the tables)

    -- enable all constraints
    exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
    

    I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).

    If you are deleting all the data you may find this solution to be helpful.

    Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.

提交回复
热议问题