0

我试图了解 TSQL 中的部分回滚。按照教程,我找到了这个示例,但我不明白/如果第一个对象失败,您可以将第二个对象保存到表中吗?

BEGIN TRAN
PRINT 'First Transaction: ' + CONVERT(VARCHAR,@@TRANCOUNT)

INSERT INTO People VALUES ('Tom')

BEGIN TRAN
PRINT 'Second Transaction: ' + CONVERT(VARCHAR,@@TRANCOUNT)

INSERT INTO People VALUES ('Dick')

ROLLBACK TRAN
PRINT 'Rollback: ' + CONVERT(VARCHAR,@@TRANCOUNT)

那么如果“汤姆”失败了,我可以拯救“迪克”吗?我需要这个,以实现多对多回滚事务。所以我创建了 Obj A,Obj B,如果两个都成功添加 Obj C,如果不是回滚失败,并保持成功的 INSERT 查询。

4

1 回答 1

1

看起来您只想在交易成功时提交交易。下面的代码保留了汤姆,即使你的脚本让迪克窒息......

CREATE TABLE #People
    ( 
        VAL VARCHAR(100)
    );

DECLARE @stop BIT = 0;
BEGIN TRY
    BEGIN TRAN
    PRINT 'First Transaction: ' + CONVERT(VARCHAR,@@TRANCOUNT)

    INSERT INTO #People VALUES ('Tom')
    COMMIT 
END TRY
BEGIN CATCH
    ROLLBACK TRAN;
    SET @stop = 1;
END CATCH;
SELECT * FROM #People;

IF @stop = 0
BEGIN TRY
    BEGIN TRAN
    PRINT 'Second Transaction: ' + CONVERT(VARCHAR,@@TRANCOUNT)

    INSERT INTO #People VALUES ('Dick');
    SELECT * FROM #People;

    RAISERROR(
        'Choke on Dick' -- stop snickering
        , 16
        , 1
        );

    COMMIT;
END TRY
BEGIN CATCH
    PRINT 'Rollback: ' + CONVERT(VARCHAR,@@TRANCOUNT)
    ROLLBACK TRAN
END CATCH

SELECT * FROM #People;

DROP TABLE #People;
于 2013-05-29T22:43:54.117 回答