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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With