【转载自:https://www.cnblogs.com/ideacore/p/7614472.html】
当表之间有主外键关系时删除数据会被约束,添加、删除失败
解决办法,我们可以先把主外键关系的检查约束给关掉 → 然后删除数据 → 之后再把约束打开
查询出关掉所有外键约束的语句
SELECT 'ALTER TABLE ' + O.NAME + ' NOCHECK CONSTRAINT [' + F.NAME + '];' AS COMMAND FROM SYS.FOREIGN_KEYS F INNER JOIN SYS.ALL_OBJECTS O ON F.PARENT_OBJECT_ID = O.OBJECT_ID WHERE O.TYPE = 'U' AND F.TYPE = 'F';
查询出开启所有外键约束的语句,与上面的区别是将 NOCHECK 改为 CHECK
SELECT 'ALTER TABLE ' + O.NAME + ' CHECK CONSTRAINT [' + F.NAME + '];' AS COMMAND FROM SYS.FOREIGN_KEYS F INNER JOIN SYS.ALL_OBJECTS O ON F.PARENT_OBJECT_ID = O.OBJECT_ID WHERE O.TYPE = 'U' AND F.TYPE = 'F';