Rollback the inner transaction of nested transaction

后端 未结 5 1863
天命终不由人
天命终不由人 2020-12-05 02:43

suppose I have following sql statement in sql server 2008:

BEGIN TRANSACTION    
SqlStatement1    
EXEC sp1    
SqlStatement3
COMMIT TRANSACTION
5条回答
  •  失恋的感觉
    2020-12-05 03:28

    Nested transactions can be used. To only rollback the inner transaction, use a savepoint and rollback to the savepoint. In case the inner transaction does not whether it is nested or not, IF statements can be used to find out whether to set a savepoint and whether to rollback or to rollback to a savepoint:

    BEGIN TRAN
    
        DECLARE @WILL_BE_NESTED_TRANSACTION BIT = CASE WHEN (@@TRANCOUNT > 0) THEN 1 ELSE 0 END
        IF @WILL_BE_NESTED_TRANSACTION = 1
            SAVE TRAN tran_save
        BEGIN TRAN
            -- do stuff
    
        IF @WILL_BE_NESTED_TRANSACTION = 1
            ROLLBACK TRAN tran_save
        ELSE
            ROLLBACK
    
    ROLLBACK
    

提交回复
热议问题