什么是级联删除?什么是级联更新?什么是级联置空?

2021/12/22 23:22:05

本文主要是介绍什么是级联删除?什么是级联更新?什么是级联置空?,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

外键的级联删除:如果父表中的记录被删除,则子表中对应的记录自动被删除 父表——被外键引用的表 子表——引用父表中的键作为外键的表  

1.解释:

父表中删除包含主键值的行的操作,该值由子表的现有行中的外键列引用。在级联删除中,删除父表中的记录时,同时删除子表中外键引用此主键的记录。 例: employee 表中有员工的dept_id 引用department表中dept_id( 同时为deptartment主键 )作为外键,当department表(父表)中一个部门被删除,employee表(子表)中引用这个部门的dept_id作为dept_id的记录也自动被删除。

2.语法:

Foreign Key (column[,...n]) references referenced_table_name[(ref_column[,...n])] [on delete cascade] [on update cascade]

3.注释:

column:列名 referenced_table_name:外键参考的主键表名称 ref_name:外键要参考的表的主键列 on delete:删除级联 on update:更新级联 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,声明了级联删除

4.测试数据:

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'    

5.级联置空:

 

 



这篇关于什么是级联删除?什么是级联更新?什么是级联置空?的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程