Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use nested stored procedure results in calling stored procedure Sql Server 2008

Is it possible to use the results of one stored procedure in another stored procedure?

I.e.

CREATE PROCEDURE [dbo].[Proc1]
        @ID INT,
        @mfgID INT,
        @DealerID INT

AS
BEGIN

    DECLARE @Proc1Result UserDefinedTableVariable

    EXEC @Proc1Result = Proc2
        @SomeID = @ID,
        @SomeID2 = @mfgID,
        @SomeID3 = @DealerID

    -- Now I want to use the table returned by the stored procedure here.
    SELECT [col1],[col2] FROM @Proc1Result

END

I tried using INSERT INTO @Proc1Result EXEC Proc2 (with parameters passed), but INSERT EXEC cannot be called in a nested statement.

Is there any way of accomplishing this? The environment is SQL Server 2008.

like image 557
JD Stuart Avatar asked Feb 02 '11 22:02

JD Stuart


People also ask

How can call nested stored procedure in SQL Server?

Here is an example of how to call a stored procedure inside another stored procedure. This is also known as nested stored procedures in SQL Server. Step 1: Create two simple stored procedure to insert some data into two different tables. both accept four parameters to insert the data.

Can we use nested stored procedure in SQL?

Nesting stored procedures and transactions present a special challenge, and SQL Server has additional rules and behavior changes to work with them. Some techniques that may work with just one stored procedure call, or one transaction level, will not work in a deeper nesting level.

Can a stored procedure call another stored procedure?

In releases earlier than SQL Server 2000, you can call one stored procedure from another and return a set of records by creating a temporary table into which the called stored procedure (B) can insert its results or by exploring the use of CURSOR variables.

When a stored procedure is executed which nesting level stores the execution?

We can nest stored procedures and managed code references in SQL Server up to 32 levels only. This is also applicable for function, trigger, and view. The current nesting level of a stored procedure's execution is stored in the @@NESTLEVEL function.


1 Answers

You can nest stored procedures up to 32 levels.

I would recommend reading over this article regarding INSERT-EXEC. Here is a snippit:

If some_sp tries to call some_other_sp with INSERT-EXEC, you will get an error message. Thus, you can only have one INSERT-EXEC active at a time. This is a restriction in SQL Server.

like image 170
Abe Miessler Avatar answered Oct 25 '22 11:10

Abe Miessler