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;

SQL Server 临时禁用和启用所有外键约束

--获得禁用所有外键约束的语句
select  'ALTER TABLE ['  + b.name +  '] NOCHECK CONSTRAINT ' +  a.name +';'  
from  sysobjects  a ,sysobjects  b    
where  a.xtype ='f' and  a.parent_obj = b.id


--获得启用所有外键约束的语句
select  'ALTER TABLE [' + b.name +  '] CHECK CONSTRAINT ' +  a.name +';'  
from  sysobjects  a ,sysobjects  b    
where  a.xtype ='f' and  a.parent_obj = b.id

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吾爱大数据

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值