sql try/catch rollback/commit - preventing erroneous commit after rollback

后端 未结 5 670
渐次进展
渐次进展 2020-12-12 21:41

I am trying to write an MS sql script that has a transaction and a try/catch block. If it catches an exception, the transaction is rolled back. If not, the transaction is

5条回答
  •  旧时难觅i
    2020-12-12 22:22

    I always thought this was one of the better articles on the subject. It includes the following example that I think makes it clear and includes the frequently overlooked @@trancount which is needed for reliable nested transactions

    PRINT 'BEFORE TRY'
    BEGIN TRY
        BEGIN TRAN
         PRINT 'First Statement in the TRY block'
         INSERT INTO dbo.Account(AccountId, Name , Balance) VALUES(1, 'Account1',  10000)
         UPDATE dbo.Account SET Balance = Balance + CAST('TEN THOUSAND' AS MONEY) WHERE AccountId = 1
         INSERT INTO dbo.Account(AccountId, Name , Balance) VALUES(2, 'Account2',  20000)
         PRINT 'Last Statement in the TRY block'
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        PRINT 'In CATCH Block'
        IF(@@TRANCOUNT > 0)
            ROLLBACK TRAN;
    
        THROW; -- raise error to the client
    END CATCH
    PRINT 'After END CATCH'
    SELECT * FROM dbo.Account WITH(NOLOCK)
    GO
    

提交回复
热议问题