Catch Block: Variables vs System Functions?

  • I am creating a single stored procedure to log errors from within the CATCH blocks in my code.

    I notice that in most of the code examples I've seen, it is common to declare a series of variables and assign error codes to them using built-in system functions:

    DECLARE @ErrMsg NVARCHAR(2048)

    SET @ErrMsg = ERROR_MESSAGE()

    INSERT INTO...@ErrMsg...etc.

    Aside from the obvious flexibility to modify the variables (which I don't think I need), is there a good reason to take these extra steps instead of just doing this?:

    INSERT INTO...ERROR_MESSAGE()...etc.


    "If I had been drinking out of that toilet, I might have been killed." -Ace Ventura

  • autoexcrement (5/27/2014)


    I am creating a single stored procedure to log errors from within the CATCH blocks in my code.

    I notice that in most of the code examples I've seen, it is common to declare a series of variables and assign error codes to them using built-in system functions:

    DxECLARE @ErrMsg NVARCHAR(2048)

    SET @ErrMsg = ERROR_MESSAGE()

    IxNSERT INTO...@ErrMsg...etc.

    Aside from the obvious flexibility to modify the variables (which I don't think I need), is there a good reason to take these extra steps instead of just doing this?:

    IxNSERT INTO...ERROR_MESSAGE()...etc.

    I think this is a holdover habit people developed when using @@ERROR, which unlike the ERROR_xxx() functions, always returns the error number of the immediately preceding T-SQL statement or a 0 if no error occurred. If you didn't catch the output of @@ERROR in a variable immediately after the statement that produced the error and ran any other T-SQL statements before calling @@ERROR, you lost the error number of interest. The ERROR_xxx() functions only work inside a CATCH block and always return information about the error that caused the CATCH block to execute no matter how many times they are called or what other code runs in the CATCH block, so you really don't have to use variables to hold their values.

    Jason Wolfkill

  • Terrific, thank you for confirming this!


    "If I had been drinking out of that toilet, I might have been killed." -Ace Ventura

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply