开发者

Have I to count transactions before rollback one in catch block in T-SQL?

I have next block in the end of each my stored procedure for SQL Server 2008

BEGIN TRY
    BEGIN TRAN
        -- my code
    COMMIT
END TRY
BEGIN CATCH
    IF (@@trancount > 0)
    BEGIN
        ROLLBACK
        DECLARE @message NVARCHAR(MAX)
        DECLARE @state INT
        SELECT @message = ERROR_MESSAGE(), @state = ERROR_STATE()
        RAISERROR (@message, 11, @state)
    END
END CATCH开发者_如何学C

Is it possible to switch CATCH-block to

BEGIN CATCH
    ROLLBACK
    DECLARE @message NVARCHAR(MAX)
    DECLARE @state INT
    SELECT @message = ERROR_MESSAGE(), @state = ERROR_STATE()
    RAISERROR (@message, 11, @state)
END CATCH

or just

BEGIN CATCH
    ROLLBACK
END CATCH

?


Actually, I never start a new transaction if I'm already in one.

This deals with nested stored procs, distributed TXNs and TransactionScope

Remember, there is no such thing as a nested transaction in SQL Server anyway.

DECLARE @StartTranCount int

BEGIN TRY
    SET @StartTranCount = @@TRANCOUNT
    IF @StartTranCount = 0 BEGIN TRAN
        -- my code
    IF @StartTranCount = 0 COMMIT TRAN
END TRY
BEGIN CATCH
    IF @StartTranCount = 0 AND @@trancount > 0
    BEGIN
        ROLLBACK TRAN
        DECLARE @message NVARCHAR(MAX)
        DECLARE @state INT
        SELECT @message = ERROR_MESSAGE(), @state = ERROR_STATE()
        RAISERROR (@message, 11, @state)
    END
    /*
    or just
    IF @StartTranCount = 0 AND @@trancount  
        ROLLBACK TRAN
    */
END CATCH


You need to check that there is a transaction in scope before trying to rollback.

You can use the following:

BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

This will rollback the transaction, but no error will be reported back to your application.

Check MSDN for more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜