sql – 无法回滚嵌套事务

我有SQL Server 2008,并希望做这样的交易:

begin transaction oo;

......

begin try        
    save transaction xx;
    alter table ....; -- this will fail
    alter table ....;
    alter table ....;
end try
begin catch  
    rollback transaction xx; -- error here
end catch;

......

commit transaction oo;

在回滚事务xx;中,我收到消息

3931 The current transaction cannot be committed and cannot be rolled back to a savepoint. Roll back the entire transaction.

我在这做错了什么?

更新要解释方案:

>有一个大事务“oo”,它将数据库的表结构从产品版本X更改为产品版本Y.
>在嵌套事务中,应尝试更改用户特定表(=内部事务).
>如果特定于用户的表以某种方式损坏,则不应回滚整个产品升级过程.
>另一方面,如果在主产品表升级(外部事务)期间出现其他问题,则不应升级用户特定表.

最佳答案
Reference

你必须在CATCH块内使用这一行

ROLLBACK TRANSACTION; 

这将回滚所有交易,
当你在上面的陈述中使用这个(在Q中发布)然后它会
给我们错误

The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

为此,你必须将此行放在TRY块中

COMMIT TRANSACTION oo;

最后你的陈述就是这样

BEGIN TRANSACTION oo;

BEGIN TRY        
    SAVE TRANSACTION xx;
    CREATE TABLE test (ID INT); -- this will fail from second time
    SELECT 3;

    COMMIT TRANSACTION oo;
END TRY

BEGIN catch  

    ROLLBACK TRANSACTION; 
END CATCH;

评论后更新

BEGIN TRY        
    BEGIN TRANSACTION xx1;
    select 1; -- this will always success
    COMMIT TRANSACTION xx1;

    BEGIN TRANSACTION xx2;
    CREATE TABLE test (id int); -- this will fail from second time
    COMMIT TRANSACTION xx2;

    BEGIN TRANSACTION xx3;
    select 3; -- this will fail from second time
    COMMIT TRANSACTION xx3;


END TRY

BEGIN catch  

    ROLLBACK TRANSACTION 
END CATCH;
点赞