Sql Server查询,关闭外键约束的sql

环境:SQL SERVER2008

情况:有时候,删除表数据(delete方式),会受到外键约束,导致删除失败

注意:该方式,仅对delete能用,truncate无效(truncate删除数据,还是会受到外键影响,除非删除外键,然后删除数据,再重新建立外键约束,网上有人说可以,但我测试过,依然提示外键约束问题)

解决办法:关闭检查约束 → 删除数据 → 约束打开

1)查询出,关闭外键约束的SQL

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';

2)查询出,打开外键约束的SQL  

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';

  

posted @ 2020-01-08 15:07  专注、坚持  阅读(1679)  评论(0编辑  收藏  举报