开发者

Why is ERROR_MESSAGE() always null?

I am writing a stored procedure in sql server 2008. The problem is the @ErrorMessage out parameter is always null. It seems to be related to the ERROR_MESSAGE() function, because when I get rid of that the other part of the message is returned.

How can I get it to return the entire errorMessage?

-- Log t开发者_开发技巧ransaction
        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 

Messages output

The statement has been terminated. Starting third error block 202

Ending third error block

(1 row(s) affected)

Results

  • @ErrorCode = 202
  • @ErrorMessage = null

(1 row(s) affected)


ERROR_MESSAGE() is only valid inside a CATCH block.

Give this a shot:

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;


I believe you use the ERROR_MESSAGE() function with TRY...CATCH blocks. Check out the usage.


Because "The error functions will return NULL if called outside the scope of a CATCH block."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜