Powered By Blogger

Tuesday, July 19, 2011

Can foreign key constraints be temporarily disabled using T-SQLin SQL Server.

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).

-- 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"

Also sometimes it is handy to disable all triggers as well,

sp_msforeachtable "ALTER TABLE ? DISABLE TRIGGER all"

exec sp_msforeachtable @command1="print '?'",
@command2="ALTER TABLE ? ENABLE TRIGGER all"

No comments: