Question

The following are the tables are an example of the issue I am having:

Companies {Id}

CompanyPeople {CompanyId, PeopleId}

People {Id}

PeopleChildren {PeopleId, ChildrenId}

Children {Id}

I want to delete all the people of a company and then delete the children of the people.

I cannot delete the people without deleting the items in the join table CompanyPeople. However if I do this I cannot find which people are part of the company.

The same issue follows down to Children

What is the best way to approach this?

Was it helpful?

Solution

I would normally use table variables or temp tables to capture the data to be used first, and then perform the deletes:

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)

OTHER TIPS

You can delete the children of the people who are in the company you want to delete first by

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 = ?) 

Then only you delete the people by

delete from People where PeopleID in (select PeopleID from CompanyPeople where CompanyPeople.CompanyID = ?) 

i think i will use output clause,i think this will be fast because of no insert and few less sql statement

this is not complete

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top