11

I was reading about error handling in SQL Server in this article, and they suggest using SQL Server's GOTO in certain situations to roll back the transaction. Example:

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

This article was written nearly 10 years ago and I've heard that it's usually a bad idea to use GOTO. Is the above an ok method for error handling in SQL Server? If not, can anyone suggest a better alternative?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

2 Answers2

20

You should be using Try/Catch in SQL 2005+

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
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
8

You must incorporate SET XACT_ABORT ON in 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
Pankaj
  • 9,749
  • 32
  • 139
  • 283