【问题标题】:Why is ERROR_MESSAGE() always null?为什么 ERROR_MESSAGE() 总是为空?
【发布时间】:2011-05-19 18:18:54
【问题描述】:

我正在sql server 2008 中编写存储过程。问题是@ErrorMessage out 参数始终为空。它似乎与 ERROR_MESSAGE() 函数有关,因为当我摆脱该消息时,将返回消息的另一部分。

我怎样才能让它返回整个errorMessage?

-- Log transaction
        INSERT INTO Transactions (TxnId, TypeId, [Date], Amount)
                                    VALUES(@TxnId, @TypeId, @TransDate, @Amount)

        -- Check for errors
        IF @@ERROR <> 0
        BEGIN
            PRINT 'Starting third error block'

                SET @ErrorCode = 202
            SELECT @ErrorMessage = 'Err_TxnId_Exists - Error inserting: ' + ERROR_MESSAGE()

            PRINT @ErrorCode
            PRINT @ErrorMessage
            PRINT 'Ending third error block'

            RETURN 1
        END 

消息输出

语句已终止。 开始第三个错误块 202

结束第三个错误块

(受影响的 1 行)

结果

  • @ErrorCode = 202
  • @ErrorMessage = null

(受影响的 1 行)

【问题讨论】:

    标签: tsql sql-server-2008 stored-procedures


    【解决方案1】:

    ERROR_MESSAGE() 仅在 CATCH 块内有效。

    试一试:

    BEGIN TRY
        INSERT INTO Transactions (TxnId, TypeId, [Date], Amount)                                     
        VALUES (@TxnId, @TypeId, @TransDate, @Amount)
    END TRY
    BEGIN CATCH
            SET @ErrorCode = 202              
            SET @ErrorMessage = ERROR_MESSAGE()
            PRINT @ErrorCode              
            PRINT @ErrorMessage    
    END CATCH;
    

    【讨论】:

    • (来自文档:“[ERROR_MESSAGE] 如果在 CATCH 块范围之外调用,则返回 NULL。”)
    【解决方案2】:

    我相信您将ERROR_MESSAGE() 函数与TRY...CATCH 块一起使用。查看usage。

    【讨论】:

    • (来自文档:“[ERROR_MESSAGE] 如果在 CATCH 块范围之外调用,则返回 NULL。”)
    【解决方案3】:
    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2020-07-20
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多