10

我在这篇文章中阅读了关于 SQL Server 中的错误处理,他们建议在某些情况下使用 SQL Server 的 GOTO 来回滚事务。例子:

BEGIN TRAN
    UPDATE Authors
    SET Phone = '415 354-9866'
    WHERE au_id = '724-80-9391'

    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM

    UPDATE Publishers
    SET city = 'Calcutta', country = 'India'
    WHERE pub_id = '9999'

    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM
COMMIT TRAN

PROBLEM:
IF (@intErrorCode <> 0) BEGIN
PRINT 'Unexpected error occurred!'
    ROLLBACK TRAN
END

这篇文章写于近 10 年前,我听说使用 GOTO 通常是个坏主意。以上是 SQL Server 中错误处理的好方法吗?如果没有,任何人都可以提出更好的选择吗?

4

2 回答 2

19

您应该在 SQL 2005+中使用Try/Catch

BEGIN TRY
    BEGIN TRAN

    UPDATE Authors
    SET Phone = '415 354-9866'
    WHERE au_id = '724-80-9391'

    UPDATE Publishers
    SET city = 'Calcutta', country = 'India'
    WHERE pub_id = '9999'

    COMMIT TRAN        
END TRY
BEGIN CATCH
    PRINT 'Unexpected error occurred!'
    IF XACT_STATE() <> 0
        ROLLBACK TRAN    
END CATCH
于 2012-06-21T15:45:23.093 回答
8

您必须SET XACT_ABORT ON加入Exception handling

Begin Try
SET XACT_ABORT ON

BEGIN TRAN
    UPDATE Authors
    SET Phone = '415 354-9866'
    WHERE au_id = '724-80-9391'

    UPDATE Publishers
    SET city = 'Calcutta', country = 'India'
    WHERE pub_id = '9999'
COMMIT TRAN

End Try

Begin Catch
    Rollback Tran
End Catch
于 2012-06-22T08:52:41.713 回答