SQLServer禁用、启用外键约束
生活随笔
收集整理的這篇文章主要介紹了
SQLServer禁用、启用外键约束
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
---啟用or禁用指定表所有外鍵約束
alter table PUB_STRU NOCHECK constraint all;
alter table PUB_STRU CHECK constraint all; ---生成啟用or禁用指定表外鍵約束的sql
select 'ALTER TABLE ' + b.name + ' NOCHECK CONSTRAINT ' + a.name +';' from sysobjects a ,sysobjects b where a.xtype ='f' and a.parent_obj = b.id and b.name='表名';
select 'ALTER TABLE ' + b.name + ' CHECK CONSTRAINT ' + a.name +';' from sysobjects a ,sysobjects b where a.xtype ='f' and a.parent_obj = b.id and b.name='表名'; --生成的sql如下
ALTER TABLE PUB_STRU NOCHECK CONSTRAINT PUBSTRU_FK1;
ALTER TABLE PUB_STRU NOCHECK CONSTRAINT PUBSTRU_FK2;
ALTER TABLE PUB_STRU CHECK CONSTRAINT PUBSTRU_FK1;
ALTER TABLE PUB_STRU CHECK CONSTRAINT PUBSTRU_FK2; --查看約束狀態(查詢字典表 sys.foreign_keys,該字典表開始出現于sqlserver2005及以上版本):
select name , is_disabled from sys.foreign_keys order by name; --其中:name : 外鍵約束名稱 is_disabled : 是否已禁用
例子:
--刪除外鍵 alter table AdItem drop constraint AdOrder_AdItem_FK1--增加外鍵 alter table AdItem add constraint AdOrder_AdItem_FK1 foreign key (AI_nOrderNo) references AdOrder(AO_nOrderNo)--單個表的一個外鍵 alter table Student nocheck constraint FK__Student__SchoolN__4222D4EF alter table Student check constraint FK__Student__SchoolN__4222D4EF --單個表的所有外鍵 alter table Student nocheck constraint all alter table Student check constraint all --某個數據庫的所有表 EXEC sp_MSforeachtable @command1='alter table ? NOCHECK constraint all; EXEC sp_MSforeachtable @command1='alter table ? CHECK constraint all;?
參考:
?Enable/Disable Constraint in SQLServer?
?sp_MSforeachtable使用方法
轉載于:https://www.cnblogs.com/gguozhenqian/p/4063548.html
總結
以上是生活随笔為你收集整理的SQLServer禁用、启用外键约束的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Ajax的Time实现倒计时功能
- 下一篇: 【转载】Linux系统挂载NTFS文件系