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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Stopping Recursion

Author  Topic 

coxmg
Starting Member

16 Posts

Posted - 2012-07-06 : 11:14:28
Hey guys question for you. If I have a recursive query that is going back many levels, can anyone provide an example where you stop a recursion through a branch by testing a condition on a field on the parent record and then stopping that branch of the recursion and then starting continuing with other branches? Where or IF?

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-07-06 : 11:20:10
You would also need some logic to identify which branch you want to stop. Something like this:
WITH cte AS
(
-- anchor query here
UNION ALL
-- recursive query starts here
FROM
YourTable y
INNER JOIN cte c ON c.Id = y.ParentId
WHERE -- stop recursion at level 11 for branchid = 32
c.Level < 11 OR y.BranchId <> 32
)
-- rest of the query here.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-07-06 : 11:22:53
can you be more specific. whats the check you need to do to determine end of recursion. ideally CTE logic using WHERE should do it for you as Sunita showed

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

Go to Top of Page
   

- Advertisement -