Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Recursive delete

Author  Topic 

craigmacca
Posting Yak Master

142 Posts

Posted - 2012-01-10 : 06:20:16
Hi i have a table with a Id and ParentId field, i need a recursive query to delete items from this table and other linked tables. i can do the deleting fine i just need to know how to do a loop deleting each child

i.e.

Id = 1, ParentId = 0
Id = 2, ParentId = 1
Id = 3, ParentId = 2
Id = 4, ParentId = 2
Id = 5, ParentId = 4
Id = 6, ParentId = 5

I need to delete Id 2 which i need to loop though each child, so i would end up with

Id = 1, ParentId = 0

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-01-10 : 06:41:18
you need a recursive cte for that.

http://msdn.microsoft.com/en-us/library/ms186243.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

noamg
Posting Yak Master

215 Posts

Posted - 2012-01-10 : 11:02:49
how to get the full list by one select statement

Noam Graizer
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-01-10 : 11:11:14
check the link posted. it has a working example. its single block of code

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -