7

我的存储过程返回预期值,但 OUT 参数没有返回任何内容。在程序退出之前打印 out 参数的值,参数的值被设置并且看起来很棒。那么为什么我的测试代码没有得到任何价值呢?

USE MyDB
GO
EXECUTE sp_addmessage 
   @msgnum   = 51001, 
   @severity = 16, 
   @msgtext  = N'Resource NOT Available', 
   @lang     = 'us_english',
   @replace  = REPLACE
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetNewFileNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetNewFileNumber]
GO


CREATE PROCEDURE dbo.GetNewFileNumber
   (
      @NextFileNum  nvarchar(11) = NULL output
   )
AS
BEGIN

    set transaction isolation level serializable
    begin transaction

    declare @LockResult int;
    declare @CurrentDate date;
    declare @FileNumberDate date;
    declare @FileNumber int;

    execute @LockResult = sp_getapplock 
        @Resource    = 'GetNewFileNumber_TRANSACTION', 
        @LockMode    = 'Exclusive',
        @LockTimeout = 0
    if @LockResult <> 0
    begin
        rollback transaction
        raiserror ( 51001, 16, 1 )
        return
    end


        set @CurrentDate = CONVERT (date, GETUTCDATE());

    select @FileNumberDate = filedate, 
        @FileNumber = fileCount from  dbo._globalCounters;
    if @FileNumberDate != @CurrentDate
    begin
        set @FileNumberDate = @CurrentDate;
        set @FileNumber = 0;
    end

    set @FileNumber = @FileNumber + 1;
    update dbo._globalCounters
        set fileDate = @FileNumberDate, fileCount = @FileNumber;

    set @NextFileNum = convert(nvarchar(6), @FileNumberDate, 12) + 
        '-' + 
        RIGHT('00'+convert(nvarchar(2), @FileNumber),2);

    execute sp_releaseapplock 'GetNewFileNumber_TRANSACTION'

    commit transaction
    print 'filenum:' + @NextFileNum     
    return @FileNumber;
END

GO

--Test the procedure
DECLARE @return_value int
DECLARE @out_value nvarchar(11)
EXEC    @return_value = [dbo].[GetNewFileNumber] @out_value 
SELECT  'Return Value' = @return_value, 'Out Value' = @out_value -- Out value always     returns null?!
GO
4

2 回答 2

27

调用时需要将其标记为输出参数

EXEC    @return_value = [dbo].[GetNewFileNumber] @out_value OUTPUT
于 2013-08-29T07:58:26.540 回答
0

我有同样的问题。原来我输入的 NVARCHAR 参数之一是 NULL。当添加到输出参数 NVARCHAR 时,它将整个参数设置为 NULL。奇怪的是。如果将输入参数添加到 NVARCHAR 输出参数,请检查它们。我在这上面花了很长时间!

于 2017-03-31T15:55:23.783 回答