SQLServer禁用、啟用外鍵約束

來源:互聯網
上載者:User

標籤:style   blog   http   os   ar   使用   for   sp   資料   

---啟用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使用方法

SQLServer禁用、啟用外鍵約束

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.