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 immoral 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 the following query will help you to allow all constraints in the database.

exec sp_msforeachtable 'alter table ? with check constraint all'

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

Related Posts

Fatal Error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails.

Problem: Sometimes, we get the following error when trying to make a connection in Rails.  FATAL ERROR: Peer authentication failed for us...