1、增加
alter table tb add constraint fk_tb_ta foreign key ( aid ) references ta ( id )
如果增加時不想對已有資料強制新的約束,可以在表名後加 with nocheck
alter table tb with nocheck add constraint fk_tb_ta foreign key ( aid ) references ta ( id )
2、刪除
alter table tb drop constraint fk_tb_ta
3、禁止
alter table tbnocheck constraint fk_tb_ta
4、啟用
alter table tbcheck constraint fk_tb_ta
如果啟用時想對已有資料檢測是否符合約束,可以在表名後加 with check
alter table tb with checkcheck constraint fk_tb_ta
if object_id('tablec') is not null drop table tablec
goif object_id('tableb') is not null drop table tableb
goif object_id('tablea') is not null drop table tablea
gocreate table tablea (aid varchar(10) primary key,aname varchar(20))
insert tablea select 'a1','公司1'
gocreate table tableb (bid varchar(10) primary key,bname varchar(20),aid varchar(10) references tablea(aid) )
insert tableb
select 'b1','部門1','a1' union all
select 'b2','部門2','a1'
gocreate table tablec (cid varchar(10) primary key,cname varchar(20),bid varchar(10) references tableb(bid))
insert tablec
select 'c1','人員1','b1' union all
select 'c2','人員2','b1' union all
select 'c3','人員3','b2' union all
select 'c4','人員4','b2'
godelete tableb where bid='b1'
go/*
訊息 547,級別 16,狀態 0,第 1 行
delete 語句與 reference 約束"fk__tablec__bid__13f2c142"衝突。該衝突發生於資料庫"master",表"dbo.tablec", column 'bid'。
語句已終止。
*/alter table tablec nocheck constraint all
--alter table tablec nocheck constraint constname
/**/
delete tableb where bid='b1'
select * from tableb
select * from tablec
/*bid bname aid
---------- -------------------- ----------
b2 部門2 a1
(1 行受影響)
cid cname bid
---------- -------------------- ----------
c1 人員1 b1
c2 人員2 b1
c3 人員3 b2
c4 人員4 b2
(4 行受影響)
*/alter table tablec check constraint fk__tablec__bid__13f2c142
禁止和啟用約束
sql server 為既有表新增列 1.alter table table name 2.add null 修改列定義 1.alter table table name 2.alter column column name 3.type name null not null collate col...
禁止及啟用表的所有約束
1 單錶語句 禁止表的單個約束 alter table table name nocheck constraint constraint name 禁止表的所有約束 alter table table name nocheck constraint all 啟用表的單個約束 alter table ...
SQL SERVER中增加刪除約束
查詢使用者自建約束 select object name object id as nameofconstraint,schema name schema id as schemaname,object name parent object id as tablename,type desc as ...