Nested transactions in Sql Server

后端 未结 4 1043
情话喂你
情话喂你 2020-12-04 19:49

Imagine the following scenario:

I am using SQL Server 2005. I have a transaction that is calling, among other SQL statements, a stored procedure that also has a tran

相关标签:
4条回答
  • 2020-12-04 20:07

    With a nested transaction, a commit does not write any changes to disk, except for the top level transaction. A rollback, however works regardless of the level of the transaction, so yes, it will roll the inner transaction back.

    0 讨论(0)
  • 2020-12-04 20:11

    Absolutely yes, the top level transaction will own all the data changes until it is committed or rolled back.

    However I would encourage you to think carefully about the transaction model. The more such scenarios exist in your system the greater your exposure to locking issues. Also the computational expense of the procedure increases.

    It's remarkable how often, when rationalising SQL, I find transactions have been implemented where they just aren't required. I encourage you (and anyone working with transactions) to think carefully about why you are using them in each context and what would happen were the transaction not implemented. Just my 2c worth!

    0 讨论(0)
  • 2020-12-04 20:15

    I've tried with begin tran and commit inside the stored procedure say usp_test.
    Exec these sp with some other query as below

    update x set name='xxx'
    select * from x---contains 'xxx'
    begin tran
    update x set name='yyy'
    select * from x---contains 'yyy'
    exec usp_test
    select * from x---contains 'zzz' inside the sp
    rollback tran
    

    While executing the above query name in x table must be 'xxx' its not 'zzz' since the first begin tran rollbacked even the sp tran commit.
    So, first begin tran own the data changes.

    0 讨论(0)
  • 2020-12-04 20:16

    Yes the stored procedure will be rolled back.

    Here is the overall flow of your code:

    BEGIN TRY
    
        BEGIN TRANSACTION
    
        EXEC SotredProcedureName
    
        --Do some other activity
    
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
    
        --IF an error occurs then rollback the current transaction, which includes the stored procedure code.
        ROLLBACK TRANSACTION
    
    END CATCH
    

    Cheers, John

    0 讨论(0)
提交回复
热议问题