如何删除没有子记录的主表记录...................
比如主表a,子表b,删除子表中记录时,如果全部删除时删除主表对应的记录 如何写?
如:
a表:1
b表:
1,1,a
2,1,b
3,1,c
删除1,a ; 1,b;当删除1,c,时需要删除a表记录1. 如何写
谢谢!
------解决方案--------------------判断一下b表中是否还存在第一个字符为1的记录。
如果没有就去表a中删除一下
------解决方案--------------------DELETE FROM a表
WHERE NOT EXISTS(SELECT 1 FROM b表 WHERE 父ID=a表.ID)
------解决方案--------------------这个逻辑一般好像需要在存储过程中实现,或者写个触发器,判断一下删除后子表是否还存在主表id号的数据,如果不存在就触发删除主表
------解决方案--------------------建个外键,加上cascade属性,2个表的删除就可以同步了
------解决方案--------------------干嘛不用级联删除?
------解决方案-------------------- 用触发器判断,或用存储过程封装删除
------解决方案--------------------Create table a( ID int)
insert into a select 1
go
create table b(ID int,AID int,Name varchar(20))
go
create trigger tr_delB on b
for delete
as
begin
delete a
from deleted as d
where d.AID=a.ID and not exists(select 1 from b where AID=d.AID))
end
触发器用法
------解决方案--------------------if object_id('ta') is not null
drop table ta
create table ta ( id tinyint primary key )
insert into ta select 1 union all select 2 union all select 3
if object_id('tb') is not null
drop table tb
create table tb
(
id tinyint identity(1,1),
aId tinyint references ta(id),
value varchar(2)
)
insert into tb select 1,'a' union all select 1,'b' union all select 1,'c' union all
select 2,'a' union all select 2,'b' union all select 2,'c' union all
select 2,'a' union all select 2,'b' union all select 2,'c'
go
if object_id('tr_tb') is not null
drop trigger tr_tb
go
create trigger tr_tb on tb
for delete
as
begin
delete ta from deleted as d where d.aId = ta.id and not exists(select * from tb where d.aId = aId)
end
select * from ta
select * from tb
删除前
delete tb where id=1
delete tb where id=2
delete tb where id=3
select * from ta
select * from tb
删除后