Home > SQL Tips > Recursive CTE – maximum recursion 100 has been exhausted

Recursive CTE – maximum recursion 100 has been exhausted

One of the most benefit of CTE (Common Table Expressions) is that we can create recursive queries with them. In my previous posts I’ve discussed this topic with some good examples, link.

An incorrectly composed recursive CTE may cause an infinite loop. So recursive CTEs should be designed very carefully and the recursion level should be checked. To prevent it to run infinitely SQL Server’s default recursion level is set to 100. But you can change the level by using the MAXRECURSION option/hint. The recursion level ranges from 0 and 32,767.

If your CTEs recursion level crosses the limit then following error is thrown by SQL Server engine:
Msg 530, Level 16, State 1, Line 11
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

Let’s check this with an example discussed in MSDN TSQL forum, link:

	@startDate DATETIME,
	@endDate DATETIME

SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'

		YEAR(@startDate) AS 'yr',
		MONTH(@startDate) AS 'mm',
		DATENAME(mm, @startDate) AS 'mon',
		DATEPART(d,@startDate) AS 'dd',
		@startDate 'new_date'
		YEAR(new_date) AS 'yr',
		MONTH(new_date) AS 'mm',
		DATENAME(mm, new_date) AS 'mon',
		DATEPART(d,@startDate) AS 'dd',
		DATEADD(d,1,new_date) 'new_date'
	WHERE new_date < @endDate
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
GROUP BY mon, yr, mm
ORDER BY yr, mm

Year	Month		Days
2011	November	22
2011	December	31
2012	January		31
2012	February	29
2012	March		24

Here, by applying “OPTION (MAXRECURSION 1000)”, we can set the recursion level, so that it does not go infinite.

Note: Restriction of recursive CTE is – “A view that contains a recursive CTE cannot be used to update data”.

More info on: http://msdn.microsoft.com/en-us/library/ms175972.aspx

  1. February 8, 2015 at 10:36 am

    doesnt work in a view. any alternatives ?

    • February 9, 2015 at 1:20 pm

      While creating VIEW do not use this clause. When you are executing the VIEW use it there instead, like:

      SELECT col1, col2
      FROM vwCTE

  2. February 8, 2015 at 10:36 am

    hey, OPTION (MAXRECURSION 1000) doesnt work in a view.. any alternatives ?

  3. Dinesh
    October 29, 2014 at 11:18 am

    Thank you…

  4. Shatrughna Kumar
    December 23, 2011 at 1:06 pm

    Nice Information.

  1. January 17, 2013 at 10:31 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: