How to disable Constraints for all the tables and enable it? How to disable Constraints for all the tables and enable it? sql-server sql-server

How to disable Constraints for all the tables and enable it?


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

You may also want to do this:

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

To enable them afterwards

EXEC sp_MSforeachtable @command1="ALTER TABLE ? ENABLE TRIGGER ALL"GO-- SQL enable all constraints - enable all constraints sql server-- sp_MSforeachtable is an undocumented system stored procedureEXEC sp_MSforeachtable @command1="ALTER TABLE ? CHECK CONSTRAINT ALL"GO

Edit:
If disabling the constraints is not enough, you will have to drop the constraints.

If you're dropping and recreating the tables, you will have to recreate the foreign key constrains afterwards.

If you just need to drop the constrains, you might find this useful:
SQL DROP TABLE foreign key constraint

If you need to write a script to drop and create the constraints, you might find my post here more useful:
SQL Server: Howto get foreign key reference from information_schema?


To disable you can apply this:

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

To enable:

EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"


declare @tname varchar(128), @tschema varchar(128);declare tables cursor forselect TABLE_SCHEMA, TABLE_NAMEfrom INFORMATION_SCHEMA.TABLES;open tables;fetch next from tables    into @tschema, @tname;while @@FETCH_STATUS = 0begin    execute ('alter table [' + @tschema + '].[' + @tname + '] nocheck constraint all');    fetch next from tables        into @tschema, @tname;end;close tables;deallocate tables;