TSQL: Try-Catch Transaction in Trigger

后端 未结 9 1711
长发绾君心
长发绾君心 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:26

    Don't rollback in a trigger and there is no need to start a transaction either.

    The ROLLBACK TRANSACTION will rollback the original DML trigger and the extra trigger transaction too. So the batch will be aborted

    Edit:

    I suggest not having a "RETURN" in your catch block and simply allow the code to complete I've never ignored a trapped error in a trigger (but I do use TRY/CATCH in triggers with rollback and raiserror to re-throw) so this is a guess, but the return is probably an abnormal exit condition in the trigger

    Also, try to avoid the error condition in the first place. Change the --some more sql to avoid the error. Example, add if exists(... to test for a duplicate first or similar

提交回复
热议问题