SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Stopping Recursion
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

coxmg
Starting Member

USA
16 Posts

Posted - 07/06/2012 :  11:14:28  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 07/06/2012 :  11:20:10  Show Profile  Reply with Quote
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

India
47099 Posts

Posted - 07/06/2012 :  11:22:53  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000