Jaa


Nesting Stored Procedures

Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels. The nesting level increases by one when the called stored procedure or managed code reference begins execution and decreases by one when the called stored procedure or managed code reference completes execution. Attempting to exceed the maximum of 32 levels of nesting causes the whole calling chain to fail. The current nesting level for the stored procedures in execution is stored in the @@NESTLEVEL function.

Note

Any reference to managed code from a Transact-SQL stored procedure counts as one level against the 32-level nesting limit. Methods invoked from within managed code do not count against this limit.

When a stored procedure executes managed code by referencing a CLR routine, type, or aggregate, this reference also counts as one level of nesting. Methods invoked from within managed code do not count against this limit. The current nesting level is returned by the @@NESTLEVEL function. When a CLR stored procedure performs data access operations through the Microsoft SQL Server managed provider, an additional nesting level is added in the transition from managed code to SQL and this level is reflected in the @@NESTLEVEL function.

An error in a nested stored procedure is not necessarily fatal to the calling stored procedure. When invoking stored procedures within stored procedures, use the Transact-SQL RETURN statement to return a return code and check the return code from the calling stored procedure. In this way, you can specify the behavior of your stored procedures when errors occur. For more information about using return codes, see Returning Data Using a Return Code.

Stored procedures can even do a nested call to themselves, a technique known as recursion.

Although the nesting limit is 32 levels, Microsoft SQL Server 2005 has no limit on the number of stored procedures that can be invoked from a given stored procedure, provided that the subordinate stored procedures do not invoke other subordinate stored procedures and the maximum nesting level is never exceeded.

See Also

Other Resources

@@NESTLEVEL (Transact-SQL)
RETURN (Transact-SQL)

Help and Information

Getting SQL Server 2005 Assistance