使用SQL Server GOTO进行错误处理的不良做法?

时间:2012-06-21 15:44:03

标签: sql sql-server error-handling goto

我正在阅读this article中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中错误处理的正确方法吗?如果没有,有人可以提出更好的选择吗?

2 个答案:

答案 0 :(得分:16)

您应该在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

答案 1 :(得分:5)

您必须在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