Search
Database

SQL Server 2008 : Advanced Stored Procedure Programming and Optimization - Nested Stored Procedures

Published 6 min readBy Programming4us Editorial Team
Stored procedures can call other stored procedures, and any of those procedures can call other procedures, up to a maximum nesting level of 32 levels deep. If you exceed the 32-level nesting limit, an error message is raised, the batch is aborted, and any open transaction in the session is rolled back. The nesting level limit prevents a recursive procedure from calling itself repeatedly in an infinite loop until a stack overflow occurs. To check the depth to which a procedure is nested, you use the system function @@NESTLEVEL (see Listing 1).

Listing 1. Checking @@NESTLEVEL in Nested Stored Procedures

Although a limit exists for the number of levels to which procedures can be nested, the number of stored procedures that can be called from within a single procedure is limitless. The main-level procedure can call potentially hundreds of other procedures. As long as the other procedures never invoke another procedure, the nesting level never exceeds two.

Any stored procedure that is called from within another procedure should return a status code if an error condition occurs. Depending on the severity of the error, failure within a nested procedure does not always cause the calling procedure or batch to be aborted. Checking the error condition from a nested procedure allows you to conditionally determine whether to continue processing.

Recursive Stored Procedures

A stored procedure can call itself up to the maximum nesting level of 32. This is referred to as recursion. When might you want a stored procedure to be recursive? One common example is when you need to expand a tree relationship. Although a common table expression (CTE) can be used to recursively expand a tree relationship, internally it builds the entire tree before applying any filters to display the tree, starting at a specific level. It is also somewhat limited in how the tree is displayed (see Listing 2).

Listing 2. Using a Common Table Expression to Expand a Tree Relationship

A recursive procedure can provide a somewhat more elegant solution to expanding a tree relationship from any level in the tree. This solution also provides more control over formatting of the output. For example, the procedure in Listing 3 formats the output so that the child parts are indented within the parent part.

Listing 3. Expanding a Tree Relationship by Using a Recursive Procedure