Click here to Skip to main content
16,014,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Well, If I have this datas in table

Table:
ID --- ParentID
1 ---- null
2 ----- 1
3 ----- 2
4 ----- 2
5 ----- null

If I delete ID=1, I want to delete everything that binded with this ID
in this example I want to delete everything except ID=5
How can I do it?

In this case, It is not working

SQL
IF (EXISTS(SELECT * FROM dbo.Table_1 WHERE @ID=ParentID))
     DELETE FROM dbo.Table_1 where ID=@ID OR ParentID=@ID
ELSE
     DELETE FROM dbo.Table_1 where ID=@ID
Posted
Updated 19-Dec-10 8:10am
v2

I believe you are somewhat confused. Given an ID = 1 you will only be able to delete the record with ID = 2 since it is the only one with a direct link to the parent in question.

You could restructure your tables to have parent and child tables and use ON DELETE CASCADE

Otherwise you are going to need some recursive query to find all related child, grandchildren, great-grandchildren, etc.
 
Share this answer
 
Hi Sider89,
Try this code. it works.
SQL
With Family As
(
    Select s.ID as aid, null as parentid,s.ID as mainparentid,  0 as Depth
    From tree s Where ID = 1
    Union All
    Select s2.ID, s2.ParentId,mainparentid, Depth + 1
    From tree s2
    Join Family
    On Family.aID = s2.ParentId  )
delete t From Family f join tree t on f.aid=t.id
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900