Sqlserver_小工具_批量字段约束处理

获取所有表与表之间的外键约束
SELECT b.name,a.name,c.name FROM sys.foreign_keys a INNER JOIN sys.tables b ON a.referenced_object_id=b.object_id INNER JOIN sys.tables c ON a.parent_object_id=c.object_id

--所有约束创建语句
SELECT CONCAT('ALTER TABLE [',d.name,'] ADD  CONSTRAINT [',b.name,'] FOREIGN KEY(',e.name,') REFERENCES [',c.name,'](',f.name,')')
FROM sys.sysforeignkeys a
INNER JOIN sys.foreign_keys b ON a.constid=b.object_id
INNER JOIN sys.tables c ON b.referenced_object_id=c.object_id
INNER JOIN sys.tables d ON b.parent_object_id=d.object_id
INNER JOIN sys.syscolumns e ON a.fkey=e.colid AND e.id=a.fkeyid
INNER JOIN sys.syscolumns f ON a.rkey=f.colid AND f.id=a.rkeyid
WHERE a.constid=2078630448

--所有约束删除语句
SELECT CONCAT('ALTER TABLE [',d.name,'] DROP CONSTRAINT [',b.name,']')
FROM sys.sysforeignkeys a
INNER JOIN sys.foreign_keys b ON a.constid=b.object_id
INNER JOIN sys.tables c ON b.referenced_object_id=c.object_id
INNER JOIN sys.tables d ON b.parent_object_id=d.object_id

 

posted on 2017-10-16 02:58  Thancoo  阅读(473)  评论(0编辑  收藏  举报

导航