如何在我的场景中的存储过程中创建输出参数?

时间:2017-04-29 19:58:30

标签: sql sql-server stored-procedures output-parameter

我有一个查询,它会将数据插入到我的表中,它应该返回一个值

我的存储过程

ALTER PROC FspCreateRequest 
@RequestDescription nvarchar(200),
@CreatedBy varchar(30),
@CreatedDate datetime,
@Region nchar(10),
@RequestID varchar(20) output
AS
BEGIN
    DECLARE @maxRequestID AS varchar(20)
    SELECT @maxRequestID=max(RequestID) 
    FROM [F_CheckRequest]
    WHERE Region = @Region

    IF (@maxRequestID IS Null or @maxRequestID = '')
    BEGIN

        IF(@Region = 'Jeddah')
        BEGIN

            INSERT INTO [F_CheckRequest
                (RequestID,RequestDescription,CreateBy,CreatedDate,Region) 
            VALUES 
               ('10001',@RequestDescription,@CreatedBy,@CreatedDate,@Region)

            SELECT @RequestID = '10001'
        END
        ELSE
        BEGIN
            INSERT INTO [F_CheckRequest] 
                (RequestID,RequestDescription,CreateBy,CreatedDate,Region) 
            VALUES 
               ('50001',@RequestDescription,@CreatedBy,@CreatedDate,@Region)

            SELECT @RequestID = '50001'
        END
    END
    ELSE
    BEGIN
        SET @maxRequestID=@maxRequestID+1;
        INSERT INTO [F_CheckRequest] 
             (RequestID,RequestDescription,CreateBy,CreatedDate,Region) 
        VALUES 
         (@maxRequestID,@RequestDescription,@CreatedBy,@CreatedDate,@Region)

        SELECT @RequestID = @maxRequestID
    END
END

当我通过以下代码

运行此查询时
EXECUTE FspCreateRequest @RequestDescription='descriotion',@CreatedBy='sa',@CreatedDate='2017-01-10',@Region='Mecca',@ReqID out
PRINT 'RequestID'+ @ReqID 

抛出错误

  

消息137,级别15,状态2,行2必须声明标量变量“@ReqID”。

     

消息137,级别15,状态2,行3必须声明标量变量“@ReqID”。

更新

是的我错了。我错过了声明输出参数。但在我执行如下之后

DECLARE @ReqID varchar(30)
EXECUTE FspCreateRequest @RequestDescription='descriotion',@CreatedBy='sa',@CreatedDate='2017-01-10',@Region='Jeddah',@ReqID out
PRINT 'RequestID'+ @ReqID 

仍然会出现如下错误

  

Msg 119,Level 15,State 1,Line 3

     

必须将参数编号5和后续参数作为'@name = value'传递。在使用'@name = value'形式后,所有后续参数必须以'@name = value'的形式传递。

1 个答案:

答案 0 :(得分:1)

这是正确答案

DECLARE @ReqID varchar(30);
EXEC FspCreateRequest @RequestDescription='descriotion',@CreatedBy='sa',@CreatedDate='2017-01-10',@Region='Mecca',@RequestID = @ReqID out;
PRINT 'RequestID'+ @ReqID ;

谢谢 @DanGuzman