raiserror显示一条消息,但不显示另一条消息

时间:2015-07-23 14:17:32

标签: sql sql-server sql-server-2012

我有这段代码:

DECLARE
   @timestamp varchar(20),
   @latestFeed INT,
   @LargestKeyProcessed INT,
   @NextBatchMax INT,
   @RC INT;

   SET @timestamp = CAST(CURRENT_TIMESTAMP as varchar(20));
   SET @latestFeed = (SELECT MAX([feed_id]) FROM [dbo].[CAQH_RESP_ALL_TEST_MIRROR]);
   SET @LargestKeyProcessed = (SELECT MIN([record_id]) - 1 FROM [dbo].[CAQH_RESP_ALL_TEST_MIRROR] WHERE [feed_id] = @latestFeed);
   SET @NextBatchMax = 1;
   SET @RC = (SELECT MAX([record_id]) FROM [dbo].[CAQH_RESP_ALL_TEST_MIRROR]);

raiserror(@timestamp, 0, 1) with nowait
raiserror(@LargestKeyProcessed, 0, 2) with nowait

WHILE (@NextBatchMax < @RC)
BEGIN
    BEGIN TRY
        --do some stuff

        COMMIT TRANSACTION flagHandling
        raiserror('Transaction Committed', 0, 3) with nowait
        raiserror(@timestamp, 0, 4) with nowait
        raiserror(@LargestKeyProcessed, 0, 5) with nowait
    END TRY
    BEGIN CATCH
        --catch some stuff
    END CATCH
END

它似乎运行良好,但有一些对我来说很奇怪的事情。在开始时,它打印日期,因为我希望看到它,但然后打印一个实际的错误消息与我正在使用的raiserror。我使用完全相同的语法,但只打印一个所需的时间戳,而下一个生成

Jul 23 2015  9:09AM
Msg 18054, Level 16, State 1, Line 16
Error 33218606, severity 0, state 2 was raised, but no message with that    
error number was found in sys.messages. If error is larger than 50000, 
make sure the user-defined message is added using sp_addmessage.

然后,在提交事务后,它会正确显示以下消息:

Transaction Committed
Jul 23 2015  9:11AM

但是遗漏了应该显示@LargestKeyProcessed值的最后一条消息。此raiserror消息与脚本开头的raiserror消息相同,产生上述奇怪的行为。

我只是希望将消息打印到消息窗口而不会出现错误,并且还希望打印所有消息。我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

你给了raiserror一个int,这意味着你正在使用msg_id功能:

RAISERROR ( { msg_id | msg_str | @local_variable }
    { ,severity ,state }
    [ ,argument [ ,...n ] ] )
    [ WITH option [ ,...n ] ]

MSG_ID:

  

是否在sys.messages中存储了用户定义的错误消息编号   使用sp_addmessage进行目录视图。用户定义错误的错误号   消息应大于50000.如果未指定msg_id,   RAISERROR引发错误消息,错误编号为50000。

您应该使用varchar变量,然后可以包含要发送的数字。请参阅documentation