sql2000三个表的级联删除

sql2000中三个表级联删除

create table a
(
    id int primary key,
    Content varchar(50)
)

create table b
(
    id int primary key,
    a_id int
)

create table c
(
    id int primary key,
    b_id int
)

a,b,c三个表,b表的外键是a表的主键,c表的外键是b表的主键。
删除a中数据,b和c中的相关数据也被删除,这时用触发器
--建立a表的触发器
create trigger dela on a
instead of delete
as
begin
declare @aID int
select @aID=id from deleted
delete from c where b_id in (select id from b where a_id=@aID)
delete from b where a_id=@aID
delete from a where id=@aID
end

删除b表中数据,c中的相关数据也被删除


用外键实现两个表的级联删除
--建立c表外键
alter table c add constraint fk_c_b foreign key (b_id) references b(id) on delete cascade

你可能感兴趣的:(sql2000)