--对表建立级联更新或级联删除方法
--1.在建表时直接定义级联更新和级联删除
create table pktable
(ID int
primary key,
SCD int,
SName varchar(20))
create table fktable
(ID int primary key,
SCD int references
pktable(ID) on delete cascade on update cascade,
Age tinyint)
insert into pktable values(‘1001‘,‘125‘,‘杨贤亮‘)
insert into pktable
values(‘1002‘,‘126‘,‘杨梓民‘)
insert into pktable
values(‘1003‘,‘127‘,‘张成锤子‘)
insert into fktable values(‘0001‘,‘1001‘,‘20‘)
insert into fktable
values(‘0002‘,‘1002‘,‘20‘)
insert into fktable values(‘0003‘,‘1003‘,‘20‘)
delete from pktable where ID=1003
--2.在建立表结束后在对表赋予级联更新和级联删除属性
create table pktable
(ID int primary
key,
SCD int,
SName varchar(20))
create table fktable
(ID int primary key,
SCD int references
pktable(ID),
Age tinyint)
exec sp_helpconstraint ‘fktable‘ --查看fktable表的所有信息,包括约束,类型,等等
alter table fktable --选择表fktable
--这是我的建标时外键的约束,小伙伴们看可以根据sp_helpconstraint语句来查询自己想要的约束名字
drop constraint
FK__fktable__SCD__1CF15040 --删除名字为 FK__fktable__SCD__1CF15040 的约束
alter table fktable
drop constraint fk_ygid_xsygid
alter table fktable
add constraint fk_ygid_xsygid
--为接下来要定义的约束起一个名字
foreign key(SCD) references pktable(ID)
on update
cascade
on delete cascade
insert into pktable values(‘1001‘,‘125‘,‘杨贤亮‘)
insert into pktable
values(‘1002‘,‘126‘,‘杨梓民‘)
insert into pktable
values(‘1003‘,‘127‘,‘张成锤子‘)
insert into fktable values(‘0001‘,‘1001‘,‘20‘)
insert into fktable
values(‘0002‘,‘1002‘,‘20‘)
insert into fktable values(‘0003‘,‘1003‘,‘20‘)
delete from pktable where ID=1003
select * from pktable
select * from fktable
建表时和建表后的级联更新和删除,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/paulzhangh/p/3750667.html