Executing a stored procedure inside BEGIN/END TRANSACTION

前端 未结 7 1085
谎友^
谎友^ 2020-12-13 06:28

If I create a Stored Procedure in SQL and call it (EXEC spStoredProcedure) within the BEGIN/END TRANSACTION, does this other stored procedure also fall into the

7条回答
  •  一向
    一向 (楼主)
    2020-12-13 06:46

    As Chris mentioned, you should be careful about rolling the transaction back.

    Specifically this:

    IF @@TRANCOUNT > 0 ROLLBACK
    

    is not always what you want. You could do something like this

    IF(@@TRANCOUNT = 1) ROLLBACK TRAN
    ELSE IF(@@TRANCOUNT > 1) COMMIT TRAN
    RETURN @error
    

    This way, the calling proc can inspect the return value from the stored procedure and determine if it wants to commit anyways or continue to bubble up the error.

    The reason is that 'COMMIT' will just decrement your transaction counter. Once it decrements the transaction counter to zero, then an actual commit will occur.

提交回复
热议问题