主外键 设置 on update cascade 和on delete cascade 的区别 SQL级联删除——删除主表同时删除从表——同时删除具有主外键关系的表

on update cascade 和on delete cascade 的区别

这是数据库外键定义的一个可选项,用来设置当主键表中的被参考列的数据发生变化时,外键表中响应字段的变换规则的。
update 则是主键表中被参考字段的值更新,delete是指在主键表中删除一条记录:
on update 和 on delete 后面可以跟的词语有四个
no action , set null , set default ,cascade
no action 表示 不做任何操作,
set null 表示在外键表中将相应字段设置为null
set default 表示设置为默认值
cascade 表示级联操作,就是说,如果主键表中被参考字段更新,外键表中也更新,主键表中的记录被删除,外键表中改行也相应删除。
级联更新时,依据的是之前匹配的数据,在主表更新关联的外键字段的值后,系统自动更新从表的相应外键字段的值,而不是其他未设置为主外键关联的字段,不是主外键关联的字段不受影响。

SQL级联删除——删除主表同时删除从表——同时删除具有主外键关系的表

 

create table a
(
id  varchar(20) primary key,
password varchar(20) not null
)

create table b
(
id int identity(1,1)  primary key,
name varchar(50) not null,
userId varchar(20),
foreign key (userId) references a(id) on delete cascade
)
表B创建了外码userId 对应A的主码ID,声明了级联删除
测试数据:
insert a values ('11','aaa')
insert a values('23','aaa')
insert b values('da','11')
insert b values('das','11')
insert b values('ww','23')
删除A表内id为‘11’的数据,发现B表内userId 为“11”也被数据库自动删除了,这就是级联删除
delete a where id='11'

create table a
(
id  varchar(20) primary key,
password varchar(20) not null
)

create table b
(
id int identity(1,1)  primary key,
name varchar(50) not null,
userId varchar(20),
foreign key (userId) references a(id) on delete cascade
)
表B创建了外码userId 对应A的主码ID,声明了级联删除
测试数据:
insert a values ('11','aaa')
insert a values('23','aaa')
insert b values('da','11')
insert b values('das','11')
insert b values('ww','23')
删除A表内id为‘11’的数据,发现B表内userId 为“11”也被数据库自动删除了,这就是级联删除
delete a where id='11'

create table a
(
id  varchar(20) primary key,
password varchar(20) not null
)

create table b
(
id int identity(1,1)  primary key,
name varchar(50) not null,
userId varchar(20),
foreign key (userId) references a(id) on delete cascade
)
表B创建了外码userId 对应A的主码ID,声明了级联删除
测试数据:
insert a values ('11','aaa')
insert a values('23','aaa')
insert b values('da','11')
insert b values('das','11')
insert b values('ww','23')
删除A表内id为‘11’的数据,发现B表内userId 为“11”也被数据库自动删除了,这就是级联删除
delete a where id='11'

猜你喜欢

转载自www.cnblogs.com/itjeff/p/11578721.html