mssql disable foreign key constraint

Solutions on MaxInterview for mssql disable foreign key constraint by the best coders in the world

showing results for - "mssql disable foreign key constraint"
Gaëlle
15 Jan 2018
1If you want to disable all constraints in the database just run this code:
2
3-- disable all constraints
4EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
5To switch them back on, run: (the print is optional of course and it is just listing the tables)
6
7-- enable all constraints
8exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
9I 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).
10
11If you are deleting all the data you may find this solution to be helpful.
12
13Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.