TSQL: Try-Catch Transaction in Trigger

后端 未结 9 1714
长发绾君心
长发绾君心 2020-12-05 08:09

I am trying to put a try-catch statement inside a trigger using Microsoft Server 2005.

BEGIN TRANSACTION
BEGIN TRY
    --Some More SQL
    COMMIT TRANSACTION         


        
9条回答
  •  不知归路
    2020-12-05 08:33

    To avoid losing the transactional data prior to the trigger action, you'll want to call COMMIT TRAN. Do this before the TRY/CATCH block and you will get your desired results.

    Example:

    COMMIT TRAN
    BEGIN TRY
        -- possible error occurs here...
    END TRY
    BEGIN CATCH
        PRINT 'Error on line ' + CAST(ERROR_LINE() AS VARCHAR(10))
        PRINT ERROR_MESSAGE()
    END CATCH
    

    It will throw the following error still - not sure how to avoid:

    The transaction ended in the trigger. The batch has been aborted.
    

    But both the original transaction and the trigger transaction should commit successfully.

    UPDATE: To avoid the exception last error, call BEGIN TRAN within the TRY statement. Note, Microsoft recommends to NOT call COMMIT TRAN within a trigger, but if unavoidable, this should work for you.

    Example:

    COMMIT TRAN
    BEGIN TRY
        BEGIN TRAN
    

提交回复
热议问题