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

后端 未结 5 667
渐次进展
渐次进展 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条回答
  •  醉酒成梦
    2020-12-12 22:23

    Below might be useful.

    Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

    BEGIN TRANSACTION;
    
    BEGIN TRY
        -- your code --
    END TRY
    BEGIN CATCH
        SELECT 
            ERROR_NUMBER() AS ErrorNumber
            ,ERROR_SEVERITY() AS ErrorSeverity
            ,ERROR_STATE() AS ErrorState
            ,ERROR_PROCEDURE() AS ErrorProcedure
            ,ERROR_LINE() AS ErrorLine
            ,ERROR_MESSAGE() AS ErrorMessage;
    
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
    END CATCH;
    
    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION;
    GO
    

提交回复
热议问题