如何将存储过程返回值存储在表或变量中

时间:2016-08-31 05:52:28

标签: sql-server tsql stored-procedures sql-insert

我有一个存储过程,我想在其中存储由另一个存储过程返回的值,我该怎么做。我尝试用Google搜索,但无法成功。我的代码是:

declare @t table (name varchar(100))      
declare @MprNum varchar(20)      
insert @t exec usp_GetNextInvoice 'MPRId','MPRNo','MPRMain'       
select @MprNum=name from @t 

我也试过这个:

create table #t(name varchar(100))
declare @MprNum varchar(20)
insert #t exec usp_GetNextInvoice 'MPRId','MPRNo','MPRMain'
select @MprNum=name from #t 

但没有成功。

3 个答案:

答案 0 :(得分:0)

试试这个

INSERT INTO #t
    EXEC usp_GetNextInvoice 'MPRId','MPRNo','MPRMain'

答案 1 :(得分:0)

如果您想将结果输出到变量,如下所示。

--Procedure :
CREATE PROCEDURE usp_GetNextInvoice 
@MPRId int,
@MprNum int OUTPUT
AS  

    SET NOCOUNT ON;

    SELECT @MprNum = MprNum
    FROM YourTable T
     WHERE T.MPRId = @MPRId

RETURN
GO

-- Execution step
DECLARE @Result int;
EXECUTE usp_GetNextInvoice 10, @MprNum = @Result OUTPUT;
SELECT @Result

如果要将结果集输出到表格,请尝试使用以下脚本

--Procedure
CREATE PROCEDURE usp_GetNextInvoice 
@MPRId int
AS  

    SET NOCOUNT ON;

    SELECT *
    FROM YourTable T
     WHERE T.MPRId = @MPRId

RETURN
GO

--execution step
CREATE TABLE #T
(Col1 ...  -- column count should match with the output of the procedure
 ....)
GO

INSERT INTO #T
EXEC usp_GetNextInvoice 10

答案 2 :(得分:0)

此语句是否返回任何行?

exec usp_GetNextInvoice 'MPRId','MPRNo','MPRMain'

因为你尝试的代码很完美......