T-SQL级联删除——ON DELETE CASCADE

ON DELETE CASCADE

创建两张表:

create table class
(
	Id int identity(1,1) primary key,
	cname nvarchar(20)
)
GO

create table student(
	Id int identity(1,1) primary key,
	sname nvarchar(20),
	cid int references class(id) on delete cascade--级联删除
)
GO

插入测试数据:

insert into class
select 'C1' union
select 'C2' union
select 'C3'

insert into student
select 'N1',1 union
select 'N2',1 union
select 'N3',2

删除class中的数据前:

--Class

Id          cname
----------- --------------------
1           C1
2           C2
3           C3

--Student
Id          sname                cid
----------- -------------------- -----------
1           N1                   1
2           N2                   1
3           N3                   2


删除数据:

delete from class where id = 1;

删除后:

--Class

Id          cname
----------- --------------------
2           C2
3           C3

--Student
Id          sname                cid
----------- -------------------- -----------
3           N3                   2


删除Class表中的数据时,Student表中引用对应的Class的数据也删除了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章