以下表格是我遇到的问题的一个例子:
公司 {Id}
公司人员 {CompanyId,PeopleId}
人 {Id}
PeopleChildren {PeopleId,ChildrenId}
儿童 {Id}
我想删除公司的所有人,然后删除人员的子女。
我不能删除人员而不删除联接表 CompanyPeople 中的项目。但是,如果我这样做,我找不到哪些人是公司的一部分。
同样的问题紧跟儿童
最好的方法是什么?
答案 0 :(得分:1)
我通常会使用table variables或temp tables来捕获首先使用的数据,然后执行删除操作:
declare @people table (PersonID int not null)
create table #children (ChildrenID int not null)
insert into @people(PersonID)
select PersonID from CompanyPeople
where CompanyID = @CompanyToRemove
insert into #children (ChildrenID)
select ChildrenID from PeopleChildren
where PersonID in (select PersonID from @people)
delete from PeopleChildren where PersonID in (select PersonID from @people)
delete from Children where ChildrenID in (select ChildrenID from #children)
delete from CompanyPeople where PersonID in (select PersonID from @people)
delete from People where PersonID in (select PersonID from @people)
答案 1 :(得分:0)
您可以通过
删除首先要删除公司的人员的子女delete from Children where ChildrenID in (select ChildrenID from Children, PeopleChildren, CompanyPeople where Children.ChildrenID = PeopleChildren.ChildrenID and PeopleChildren.PeopleID = CompanyPeople.PeopleID and CompanyPeople.CompanyID = ?)
然后只有您通过
删除人员delete from People where PeopleID in (select PeopleID from CompanyPeople where CompanyPeople.CompanyID = ?)
答案 2 :(得分:0)
我想我会使用输出子句,我认为这会很快因为没有插入而且少了几个sql语句
这不完整
declare @people table (PersonID int not null)
DELETE FROM PeopleChildren
FROM @people p INNER JOIN
PeopleChildren pc ON p.ID = pc.ID
output deleted.id into @people
delete from People p
from People inner join @people p1 on p.PersonID=p1. PersonID