T-SQL存储过程使用输出传递输入

时间:2013-10-22 21:25:46

标签: sql-server stored-procedures

对我来说很容易......还是新手T-SQL程序员:)

我有一个存储过程,用于获取三个输入参数,评估它们并发回一个参数(@eligible)。如果我只使用硬编码的变量执行T-SQL脚本,我的@@ ROWCOUNT将@eligible设置为1.当我执行对它的调用作为存储过程时,它不会正确返回@eligible。这是程序:

ALTER PROCEDURE [dbo].[proc_Eligible]
                (@control AS nvarchar(10),
                 @checkno AS nvarchar(10),
                 @event_type AS nvarchar(7),
                 @eligible AS bit OUTPUT)
AS

BEGIN
    SET @eligible = 0

    SELECT @control AS Control, @checkno AS CheckNum

    -- Is the check drawn on an eligible bank?
SELECT
        H.CONTROL,
        H.NAME,
        H.RECV_DATE,
        H.CHECK_NUM,
        H.BANK,
        SUM(D.RECV_AMOUNT)
FROM
        [ZZZ].[dbo].[MRRECVH] H INNER JOIN
        [ZZZ].[dbo].[MRRECVD] D ON H.control  = D.CONTROL
WHERE
        BANK IN (SELECT
                    RIMAS_Code
                 FROM
                    [Custom].[dbo].[Bank_Account])
    AND H.CONTROL = @control
    AND H.CHECK_NUM = @checkno
GROUP BY
        H.CONTROL,
        H.BANK,
        H.NAME,
        H.CHECK_NUM,
        H.RECV_DATE
HAVING
        SUM(D.RECV_AMOUNT) > 0

    IF @@ROWCOUNT > 0   
    SELECT @eligible = 1
END

(在最后一行的旁边,我试过'SET @eligible = 1',但这没有任何区别。)

致电程序:

DECLARE
    @eligible AS bit

EXECUTE proc_Eligible
    @Control     = '3034'
    ,@Checkno    = '5011'
    ,@event_type = 'update'
    ,@eligible   = @eligible

SELECT @eligible

正如我所提到的,如果我隔离存储过程的SELECT语句并对变量进行硬编码,那么它的工作效果很好,所以可能是我的新手缺乏传递数据的经验。

(@ event_type将在以后用于表格触发器时使用)

谢谢你, 凯文

1 个答案:

答案 0 :(得分:5)

当您调用存储过程时,似乎还必须指定OUTPUT关键字:

EXECUTE proc_Eligible
    @Control = '3034'
    ,@Checkno = '5011'
    ,@event_type = 'update'
    ,@eligible = @eligible OUTPUT  -- <--- mark parameter as output