在另一个存储过程中返回存储过程的输出参数

时间:2012-02-15 00:51:02

标签: sql-server sql-server-2008 tsql

我正在尝试找出在另一个存储过程中执行存储过程时如何返回存储过程的输出参数:

 CREATE PROCEDURE Test1

 EXEC SpWithOutputID -- Outputs @ID

 SELECT @ID as ID -- Output @ID now being used in this SP

这当然不是我的代码,只是一个例子,是否可以这样做?

示例2:       - 这里@ID返回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

示例3:       - 这里@ID返回一个Int

 CREATE PROCEDURE Test1
 As 

 EXEC SpWithOutputID -- Outputs @ID

1 个答案:

答案 0 :(得分:3)

如果这根本不是输出参数问题,而是结果集,那么假设SpWithOutputID执行类似这样的操作(返回SELECT一行并且单个列):

CREATE PROCEDURE dbo.SpWithOutputID
AS
BEGIN
    SET NOCOUNT ON;

    SELECT ID = 4;
END
GO

然后Test1看起来像这样:

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


但这对你来说不是很麻烦吗?对于单个标量值,它应该以这种方式工作:

CREATE PROCEDURE dbo.SpWithOutputID
    @ID INT OUTPUT 
AS
BEGIN
    SET NOCOUNT ON;

    SELECT @ID = 4; 
END 
GO

现在消耗真正的输出参数要简单得多:

CREATE PROCEDURE dbo.Test1
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @ID INT;

    EXEC dbo.SpWithOutputID @ID = @ID OUTPUT;

    SELECT @ID;
END
GO