Errorhandling Proc and Trigger

  • Hello!

    Having a Proc that populate a table (a) and that table has an AFTER INSERT-Trigger that populates other tables (b and c). I have implemented this errorhandling in the trigger after every INSERT to tables (b and c).

    :

    SELECT @err = @@error IF @err <> 0 BEGIN ROLLBACK TRANSACTION RETURN END

    But how can I recieve some kind of error up to the application that executed the Proc?

    Probably I whant to to rollback the insert to table (a) too !

    /Tomas

  • Thank's!

    /Tomas

  • Tomas,

    You could look into TRY/CATCH blocks. I use them all the time. They are especially handy when you want to return a particular message. Something like:

    DECLARE @ErrMsg VARCHAR(1000)

    BEGIN TRY

    INSERT INTO MyTable...

    SELECT...

    END TRY

    BEGIN CATCH

    SET @ErrMsg = 'Error Inserting MyTable...' + ERROR_MESSAGE()

    RaisError(@ErrMsg, 18, 1)

    END CATCH

    There's a lot you can do with it.

    Todd Fifield

  • Thank's

    I have this, do I need the commit or is the transaction automaticly rolled back if I go in to Catch section?

    What do you think about this code?

    BEGIN TRY

    BEGIN TRANSACTION

    UPDATE TblWeb SET Klar = 0 WHERE Filename = @p1

    UPDATE TblWebArtikles SET Klar = 0 WHERE Filename = @p1

    UPDATE TblWebAccounts SET Klar = 0 WHERE Filename = @p1

    COMMIT TRANSACTION

    END TRY

    BEGIN CATCH

    ROLLBACK TRANSACTION

    SET @ErrMsg = 'Error Update ResetKlar_sp...' + ERROR_MESSAGE()

    RaisError(@ErrMsg, 18, 1)

    END CATCH

  • Tomas,

    If you start a transaction then you have to commit it or you will have an open transaction. Normally I put the BEGIN TRAN statement before the BEGIN TRY - mostly because there is usually further processing done if the TRY is successful. It's really up to you how you handle the COMMIT.

    The CATCH block will set up the error handling, roll back the transaction and either return or go to some common exit point in the code. If you have any sort of logging results, then the roll back has to be done before inserting/updating the log table or that will get rolled back also.

    Todd Fifield

  • Thank´s a lot for the information!

    Tomas

  • Glad to help.

    Todd Fifield

Viewing 8 posts - 1 through 7 (of 7 total)

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