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.

4 comments:

  1. 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.

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

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

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

    ReplyDelete