功能:在删除主表时,自动删除副表(外键约束)相应内容
删除包含主键值的行的操作,该值由其它表的现有行中的外键列引用。在级联删除中,还删除其外键值引用删除的主键值的所有行。
如:
create database temp
go
use temp
go
create table UserInfo
(
UserId int identity(1,1) primary key ,
UserName varchar(20), --用户名
password varchar(20) not null --密码
)
create table UserDetails
(
id int identity(1,1) primary key,
name varchar(50) not null, --真实姓名
userId int,
foreign key (userId) references UserInfo(UserId) on delete cascade
)
insert UserInfo values ('ly','jeff')
insert UserInfo values('wzq','wzqwzq')
insert UserInfo values('lg','lglg')
insert UserDetails values('李四',1)
insert UserDetails values('王五',2)
insert UserDetails values('刘六',3)
此时:Delete From UserInfo Where UserId = 1 就可删除UserInfo表和UserDetails表的UserId=1 的内容
当你的已经创建好了的时候不需要修改,只需要添加上
级联删除功能就可以了,代码如下
alter table 表名
add constraint 约束名
foreign key(字段名) references 主表名(字段名)
on delete cascade
alter table 表名
add constraint 约束名
primary key(字段名)
alter table 表名
add constraint 约束名
unique key(字段名)
同事sql 还支持级联更新.
oracle 只支持级联删除