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

被刻印的时光 ゝ 提交于 2019-11-28 17:52:14
Stefan Steiger
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 procedure
EXEC 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?

SrividhyaShama

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 for
select TABLE_SCHEMA, TABLE_NAME
from INFORMATION_SCHEMA.TABLES;

open tables;

fetch next from tables
    into @tschema, @tname;

while @@FETCH_STATUS = 0
begin
    execute ('alter table [' + @tschema + '].[' + @tname + '] nocheck constraint all');
    fetch next from tables
        into @tschema, @tname;
end;

close tables;

deallocate tables;

Try to use this command

ALTER TABLE table_Name NOCHECK CONSTRAINT all

to disable all constraint for your tables, and do it for all your 10 tables , but before that check if you haven't put any Delete_Cascade on your tables because the error which is shown maybe because of sub_tables dependencies too. if it didn't work try to disable specific constraint by this command, it maybe two or three extra dependencies.

ALTER TABLE tableName NOCHECK CONSTRAINT constraintName
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!