如何使用游标中的Input和Output参数处理存储过程?

时间:2016-09-21 09:28:08

标签: sql tsql stored-procedures cursor

我有一个stored procedure,其中包含一个查询,为员工ID(output)提供varchar(input)值。

我的光标包含员工ID列表,我想循环存储过程并打印每个员工ID的值。

这是我到目前为止所尝试的:

DECLARE @MyCursor as CURSOR
DECLARE @InputPar as int
DECLARE @OutputPar as varchar(30)

SET @MyCursor = CURSOR FOR <query>

Open @MyCursor;
FETCH NEXT FROM @MyCursor INTO @InputPar

BEGIN
WHILE @@FETCH_STATUS = 0
Exec dbo.mySP @InputPar, @OutputPar Output
Print @OutputPar
FETCH NEXT FROM @MyCursor INTO @InputPar
END
CLOSE @MyCursor;
DEALLOCATE @MyCursor;

我现在得到的错误是Must declare the scalar variable "@QutputPar".变量在上面声明,所以我看不出问题出在哪里。任何人都可以帮助我运行我的代码吗?

2 个答案:

答案 0 :(得分:0)

你通过游标做的原因是未知的,它可以用基于集合的操作替换(99%的时间)。为什么你没有得到值的原因是你没有正确读取输出值..

以下是做法

   Declare @var int/varchar--delcare datatype as per u r need
    Exec dbo.mySP @InputPar, @var Output

    Print @var

答案 1 :(得分:0)

DECLARE @InputPar as int
DECLARE @OutputPar as varchar(30)
declare MyCursor cursor for <your query here>
Open MyCursor;
FETCH NEXT FROM MyCursor INTO @InputPar

Exec dbo.mySP @InputPar, @OutputPar Output
Print @OutputPar

CLOSE MyCursor;
DEALLOCATE MyCursor;