SAVE TRANSACTION vs BEGIN TRANSACTION (SQL Server) how to nest transactions nicely

前端 未结 3 1548
生来不讨喜
生来不讨喜 2020-12-24 14:10

I have a stored procedure that needs to set a save point so that it can, under certain circumstances, undo everything it did and return an error code to the caller, or accep

3条回答
  •  感动是毒
    2020-12-24 15:03

    Extending Brian B's answer.

    This ensures the save point name is unique and uses the new TRY/CATCH/THROW features of SQL Server 2012.

    DECLARE @mark CHAR(32) = replace(newid(), '-', '');
    DECLARE @trans INT = @@TRANCOUNT;
    
    IF @trans = 0
        BEGIN TRANSACTION @mark;
    ELSE
        SAVE TRANSACTION @mark;
    
    BEGIN TRY
        -- do work here
    
        IF @trans = 0
            COMMIT TRANSACTION @mark;
    END TRY
    BEGIN CATCH
        IF xact_state() = 1 OR (@trans = 0 AND xact_state() <> 0) ROLLBACK TRANSACTION @mark;
        THROW;
    END CATCH
    

提交回复
热议问题