Bad practice to use SQL Server's GOTO for error handling?
error-handling, goto, sql, sql-server
Solution
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
Problem
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?