当前位置首页 > 百科资料> 正文

级联删除

2022-07-12 06:27:57 百科资料

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

父表--被外键引用的表

子表--引用父表中的键作为外键的表

  • 中文名称 级联删除
  • 外文名称 Foreign Keys with Cascade Delete
  • 解释 其外键值引用删除主键值所有行
  • 语言 Foreign Key
  • 注释 ref_name:外键要参考的表主键列

解释:

  父表中删除包含主键值的行的操作,该值由子表的现有行中的外键列引用。在级联删除中,删除父表中的记录时,同时删除子表中外键引用此主键的记录。

  例:

  employee 表中有员工的dept_id 引用department表中dept_id( 同时为deptartment主键 )作为外键,当department表(父表)中一个部门被删除,employee表(子表)中引用这个部门的dept_id作为dept_id的记录也自动被删除。

语法:

  Foreign Key

  (column[,...n])

  references referenced_table_name[(ref_column[,...n])]

  [on delete cascade]

  [on update cascade]

注释:

  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,声明了级联删除

测试数据:

  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'

声明:此文信息来源于网络,登载此文只为提供信息参考,并不用于任何商业目的。如有侵权,请及时联系我们:baisebaisebaise@yeah.net