I'm trying to find out how to return the output parameter of a stored procedure when executing the stored procedure inside another stored procedure:
CREATE PROCEDURE Test1
EXEC SpWithOutputID -- Outputs @ID
SELECT @ID as ID -- Output @ID now being used in this SP
This is of course not my code, but just an example, is it possible to do this?
Example 2:
--Here @ID returns Null
CREATE PROCEDURE Test1
As
DECLARE @ID int
EXEC SpWithOutputID @ID = @ID OUTPUT -- Outputs @ID
SELECT @ID as ID -- Output @ID now being used in this SP
Example 3:
--Here @ID returns an Int
CREATE PROCEDURE Test1
As
EXEC SpWithOutputID -- Outputs @ID
If this isn't really an output parameter issue at all, but rather a result set, then taking a guess that SpWithOutputID
does something like this (returns a SELECT
with a single row and single column):
CREATE PROCEDURE dbo.SpWithOutputID
AS
BEGIN
SET NOCOUNT ON;
SELECT ID = 4;
END
GO
Then Test1
could look like this:
CREATE PROCEDURE dbo.Test1
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ID INT;
CREATE TABLE #x(ID INT);
INSERT #x EXEC dbo.SpWithOutputID;
SELECT TOP (1) @ID = ID FROM #x;
DROP TABLE #x;
END
GO
But doesn't that look really messy to you? It really should work this way for single, scalar values:
CREATE PROCEDURE dbo.SpWithOutputID
@ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT @ID = 4;
END
GO
Now it is much simpler to consume what is really an output parameter now:
CREATE PROCEDURE dbo.Test1
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ID INT;
EXEC dbo.SpWithOutputID @ID = @ID OUTPUT;
SELECT @ID;
END
GO