Skip to content

Recursive Common Table Expressions

2011 May 11
by Shannon Lowder

In case you haven’t had a chance to play with them Common Table Expressions (CTEs) are pretty cool.  Basically you can define a temp table and do operations against that table all on one statement.  One of the things I’ve found most awesome about CTEs is using them for recursive logic!

Here’s a contrived example of a Recursive CTE.

DECLARE @start INT = 0;
DECLARE @end INT = 100; 

WITH test(value) AS (
 SELECT value  FROM (SELECT @start AS value) AS t
 UNION ALL
 SELECT value + 1
 FROM test
 WHERE value < @end
)
SELECT value
FROM test

In this example, I set up the CTE to do a counter.  A simple use, but you can get as wild as you want with it.  I basically SELECT my @start value as the first row in my test table, and then UNION that to 1+ the highest value already defined in my test table.  That referencing back to the CTE table name you’ve defined is what makes it recursive!

The uses I’ve found for this, building hierarchical relationships in the database…Think employee – manager relationships.  You do your first query for the employee, include the managerID, then join to the employee table again matching the second employeeID to the previous managerID.

It can be much more manageable than a recursive join.  Plus you have an extra control with CTEs you don’t have with the recursive joins, MAXRECURSION.

How many times have you built a WHILE loop that never ended?  Well, when you start talking about recursion the possibility of a never ending loop is real.

SQL Server designers realize this, so they’ve added the MAXRECURSION option as a fail-safe against runawaycode.

Let’s go back to my previous example.  What if we change the @end variable to 1000?

DECLARE @start INT = 0;
DECLARE @end INT = 1000; 

WITH test(value) AS (
 SELECT value  FROM (SELECT @start AS value) AS t
 UNION ALL
 SELECT value + 1
 FROM test
 WHERE value < @end
)
SELECT value
FROM test

By default, SQL server limits the number of recursions to 100.  So you see the following error.

Msg 530, Level 16, State 1, Line 4
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

But you can adjust this by overriding that default to any number between 0 and 32767.  This is useful when you know that there are only 5 levels of hierarchy in your organization.  You simply add the MAXRECURSION option, and set the value to 5.

WITH test(value) AS (
 SELECT value  FROM (SELECT @start AS value) AS t
 UNION ALL
 SELECT value + 1
 FROM test
 WHERE value < @end
)
SELECT value
FROM test
OPTION (MAXRECURSION 5)

Msg 530, Level 16, State 1, Line 4
The statement terminated. The maximum recursion 5 has been exhausted before statement completion.

I thought you said we’d be fine by adding the MAXRECURSION option.

Well, you still have to wrap your CTE in a TRY…CATCH, but at least it didn’t run for more records than you needed.  Notice the results tab.

value
0
1
2
3
4
5

You got just 5 “levels deep”.  If you wrapped this code in a TRY CATCH, and basically ignore this one errornumber (530), you can continue with the rest of your code, knowing you’ll only ever get 5 levels deep.  Of course, as simpler way would be to set the @end variable to 5, but that only works in my contrived example.

I just want to make sure you understand how to use CTEs to create recursive logic, that you can limit the number of rows returned by setting the MAXRECURSION, and even if you exceed the recursion limit you set, you still get the number of rows in addition to an error message.

If you have any questions, please let me know!  I’m here to help you learn SQL.

 

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS