SQL。无法回滚事务

时间:2014-04-13 14:54:06

标签: sql-server tsql ssms

我尝试使用事务从表中删除几行。我使用三次命令删除,其中两次是OK,第三次包含错误。我想创建保存点并提交2个对象的删除。但是我收到一个错误:当前事务无法提交,也无法回滚到保存点。回滚整个交易。这是我的代码:

BEGIN TRANSACTION
BEGIN TRY
DELETE FROM employee
WHERE ID = 101; --OK

DELETE FROM employee
WHERE Name = 'James'; --OK

SAVE TRANSACTION point_1;

DELETE FROM employee
WHERE ID = '11a'; --letters are not allowed
COMMIT TRANSACTION
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION point_1
    PRINT 'Error! Not all employees were deleted from database.'
END CATCH

任何人都可以帮助我吗?非常感谢你!

我试过这种方式:

    BEGIN TRANSACTION
DELETE FROM employee
WHERE ID = 101;

DELETE FROM employee
WHERE Name = 'James';

SAVE TRANSACTION point_1;

BEGIN TRY
DELETE FROM employee
WHERE ID = '11a';
END TRY
BEGIN CATCH
    if XACT_STATE () = -1
        ROLLBACK TRANSACTION
    if XACT_STATE () = 1 and @@TRANCOUNT = 0
        ROLLBACK TRANSACTION
    if XACT_STATE () = 1 and @@TRANCOUNT > 0
        ROLLBACK TRANSACTION point_1
PRINT 'Error! Not all employees were deleted from database.'
END CATCH

这次没有错误,但前两个对象不会被删除。我的错误在哪里?谢谢!

1 个答案:

答案 0 :(得分:0)

您可能在会话中有SET XACT_ABORT ON。如果您的代码在触发器内,则默认情况下此设置为ON。

使用SET XACT_ABORT OFF尝试使用您的代码。