Click here to Skip to main content
5,788,961 members and growing! (20,737 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Advanced License: The Code Project Open License (CPOL)

Recursion in SQL using CTE

By Dennis Pais

This article demostrates how you can achieve a function recursion effect in SQL
SQL, SQL Server, Dev

Posted: 16 Nov 2008
Updated: 16 Nov 2008
Views: 2,425
Bookmarked: 10 times
Note: This is an unedited reader contribution
Announcements
Loading...



Search    
Advanced Search
Sitemap
6 votes for this Article.
Popularity: 2.85 Rating: 3.67 out of 5
1 vote, 16.7%
1
1 vote, 16.7%
2
0 votes, 0.0%
3
1 vote, 16.7%
4
3 votes, 50.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article
Recursive_Query_Using_CTE

Introduction

I've often wondered how to use recursion in SQL. This article shows how to use Common Table Expressions (CTE or CTE's)to do this.

Background

SQL Server 2005 introduces a neat little thingy called CTE's. These can allow to you to do most of the things that derived tables can - but it also brings with it a more powerful capability - you can now write recursive queries in SQL using set-based logic. This capability is best explained with an example, so let's get down to it right away.

Printing an employee heirarchy

Look at the Employees table in the Northwind database. You will see that each employee has a ReportsTo column value set to an Employee ID. Let's say your task is to print out an employee heirarchy for Employee ID 5. What do you do? Resort to ADO.NET? With SQL 2005 you can use CTE's to do the same. Look at the code below:

WITH CTE_EMPLOYEE_HEIRARCHY AS
(
	SELECT E.EmployeeID, E.ReportsTo AS Supervisor, E.FirstName, E.LastName
	FROM EMPLOYEES E WHERE E.EmployeeID = 5
	
	UNION ALL

	SELECT E1.EmployeeID, E1.ReportsTo AS Supervisor, E1.FirstName, E1.LastName
	FROM CTE_EMPLOYEE_HEIRARCHY 
	JOIN EMPLOYEES E1
	ON E1.ReportsTo = CTE_EMPLOYEE_HEIRARCHY.EmployeeID 

)

SELECT * FROM CTE_EMPLOYEE_HEIRARCHY		

Let's look at each little block. The 'WITH CTE_EMPLOYEE_HEIRARCHY' simply names your CTE as CTE_EMPLOYEE_HEIRARCHY. The first SELECT statement is the 'anchor'.

SELECT E.EmployeeID, E.ReportsTo AS Supervisor, E.FirstName, E.LastName
FROM EMPLOYEES E WHERE E.EmployeeID = 5

It kicks off the recursive query by returning an employee row with ID = 5.

Next, the second SELECT gets the employees that report to EMP ID 5, but that's because only in the first run. Notice that this SELECT statement refers to the CTE itself:

SELECT E1.EmployeeID, E1.ReportsTo AS Supervisor, E1.FirstName, E1.LastName
	FROM CTE_EMPLOYEE_HEIRARCHY 
	JOIN EMPLOYEES E1
	ON E1.ReportsTo = CTE_EMPLOYEE_HEIRARCHY.EmployeeID 

So this statement will return all employees who report to Employee ID = 5. In this example, there's only one level of reportees (6,7 & 9). But if Employee ID's 6,7 or 9 would have had more reportees, in the next recursion step, the CTE name would be replaced by Employee ID's 6,7 & 9, & you would get the next level of reportees.

So where does the recursion stop? By default, recusion stops at a recursive level of 100 (configurable), or when an empty result set is returned, whichever is earlier - as in the case of the above example when the second recusive call to the CTE name would get resolved to 6,7 & 9 but the resultant empty set of reportees would be empty because 6,7 & 9 are the humble software devs who have nobody to delgate work to.

License

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

About the Author

Dennis Pais



Location: India India

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralRecursion levelmemberbillove12:34 21 Nov '08  
GeneralNice and concisemembercmschick2:29 17 Nov '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 Nov 2008
Editor: Chris Maunder
Copyright 2008 by Dennis Pais
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project