SQL Server Stored Procedure Recursion Limit

In order to save you from a performance penalty, SQL Server has a hard limit set for recursion levels for Stored Procedures, Functions, Triggers  and Views. The limit is 32 levels and you can’t change it programmatically.

Here is a simple example demonstrating this limit:

CREATE PROCEDURE recurseProc (@cnt int)
AS
BEGIN
PRINT @cnt;
SET @cnt += 1;
EXEC recurseProc @cnt; 
END; 
GO

EXEC recurseProc 1;


stored-procedure-recursive


When you execute this code, you get an error after 32 recursions are over Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

Note: You can work around this limitation by using a Common Table Expression. A CTE allows up to 100 levels of recursion.


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

4 comments:

ax4413 said...

There is no recursion limit when using cte's. there is a default limit that can be extended by using the MAXRECURSION hint to 32,767. However if you set the MAXRECURSION to zero there is no recursive limit. Be careful though as there is a default limit for a reason.

Suprotim Agarwal said...

@ax4413 Yes I meant the default limit is 100. Thanks for the info about MAXRECURSION.

Prajakta Salokhe said...

please can you give proper reason... why limit is 32 for recursion?

Bear said...

Can you give an example of a good use case for this approach?