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)
PRINT @cnt;
SET @cnt += 1;
EXEC recurseProc @cnt; 

EXEC recurseProc 1;


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





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?