Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn off/on all the foreign keys and triggers in Microsoft SQL Server?

Tags:

sql

sql-server

It can be needed for inserting and modifying of big amounts of data.

like image 864
Timushev Roman Avatar asked Oct 22 '25 04:10

Timushev Roman


1 Answers

Disable all FKs:

EXEC sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
GO

Enable all FKs:

EXEC sp_MSforeachtable @command1="ALTER TABLE ? CHECK CONSTRAINT ALL"
GO

Disable all triggers:

EXEC sp_MSforeachtable @command1="ALTER TABLE ? DISABLE TRIGGER ALL"
GO

Enable all triggers:

EXEC sp_MSforeachtable @command1="ALTER TABLE ? ENABLE TRIGGER ALL"
GO

Of course, note that if you had any FKs/triggers disabled prior to this, the enable script will re-enable these.

like image 157
Jerad Rose Avatar answered Oct 23 '25 18:10

Jerad Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!