7

我有以下代码,作为一个通用示例,我想知道如果事务以RETURN.

BEGIN TRANSACTION
    BEGIN TRY
        IF NOT EXISTS(SELECT 1 FROM dbo.tblProducts WHERE intProductID = @intProductID)
            BEGIN
                SELECT 'Product does not exists' AS strMessage
                RETURN
            END

        UPDATE dbo.tblProducts SET
            curPrice = 10
        WHERE
            intProductID = @intProductID

        SELECT 'Success' AS strMessage

    END TRY 

    BEGIN CATCH
        SELECT ERROR_MESSAGE() AS strMessage
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION
    END CATCH

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION
4

4 回答 4

8

它应该像下面

BEGIN TRY
    SET NOCOUNT ON
    SET XACT_ABORT ON
    BEGIN TRANSACTION
        IF NOT EXISTS(SELECT 1 FROM dbo.tblProducts 
                          WHERE intProductID = @intProductID)
        BEGIN
            SELECT 'Product does not exists' AS strMessage
            Rollback TRan
            RETURN
        END

        UPDATE dbo.tblProducts SET
        curPrice = 10
        WHERE
        intProductID = @intProductID

        SELECT 'Success' AS strMessage
    COMMIT TRAN
END TRY 

BEGIN CATCH
    SELECT ERROR_MESSAGE() AS strMessage
    ROLLBACK TRANSACTION
END CATCH
于 2012-08-19T09:06:59.033 回答
3

我只是通过运行上面的代码然后检查SELECT @@TRANCOUNT然后尝试ROLLBACK. 返回后,@@TRANCOUNT为 1,我能够rollback成功交易,表明它处于transaction打开状态。

于 2012-08-19T02:54:06.617 回答
2

此代码适用于嵌套事务:

BEGIN TRY
   IF @@TRANCOUNT > 0
      SAVE TRANSACTION MyTransactionName
   ELSE
       BEGIN TRANSACTION MyTransactionName

    IF NOT EXISTS(SELECT 1 FROM dbo.tblProducts WHERE intProductID = @intProductID)
        BEGIN
            SELECT 'Product does not exists' AS strMessage
            ROLLBACK TRANSACTION MyTransactionName
            RETURN
        END

    UPDATE dbo.tblProducts SET
        curPrice = 10
    WHERE
        intProductID = @intProductID

    SELECT 'Success' AS strMessage

    COMMIT TRANSACTION MyTransactionName
END TRY 

BEGIN CATCH
    SELECT ERROR_MESSAGE() AS strMessage
    ROLLBACK TRANSACTION MyTransactionName
END CATCH
于 2016-01-28T20:44:07.437 回答
0

请参阅我在以下 DBA.StackExchange 答案中发布的存储过程模板,因为它解决了 TRY / CATCH 与事务的使用,并且它处理嵌套调用,即使事务是在应用程序层中打开的:

我们是否需要在 C# 代码和存储过程中处理事务

于 2016-01-28T21:26:17.987 回答