--本例以外键为例,其他约束类似
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 tb NoCheck Constraint fk_tb_ta
4、启用
Alter Table tb Check Constraint fk_tb_ta
如果启用时想对已有数据检测是否符合约束,可以在表名后加 With Check
Alter Table tb With Check Check Constraint fk_tb_ta
---测试例子:
if object_id('tableC') is not null drop table tableC
go
if object_id('tableB') is not null drop table tableB
go
if object_id('tableA') is not null drop table tableA
go
create table tableA (Aid varchar(10) primary key,Aname varchar(20))
insert tableA select 'A1','公司1'
go
create 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'
go
create 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'
go
delete 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