Skip to main content

Disable/Enable All the Foreign Key Constraint in SQL Server Database

In some scenario we need to disable all foreign key relationships from all table, suppose for bad testing purpose or you want to see what will be effect of garbage data on application or performance, due to this purpose you want to insert garbage data into table and this table contains foreign key constraints then you will get the error of foreign key constraint.

Many people face these types of issue, the following query will resolve this problem but be careful on the production server, it would be better if you do this under guidance to any DBA.

The following query will disable all constraints in the database.


exec sp_msforeachtable 'alter table ? nocheck constraint all'


Once you disabled all constraints you should also need to enable all constraints once you completed your work, so following query will help you to enable all constraints in the database.


exec sp_msforeachtable 'alter table ? with check check constraint all'


Using the above query you can resolve above described scenario but if you want to truncate table this will not be work, you have to remove all foreign key constraints.