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?
To handle exception in Sql Server we have TRY.. CATCH blocks. We put T-SQL statements in TRY block and to handle exception we write code in CATCH block. If there is an error in code within TRY block then the control will automatically jump to the corresponding CATCH blocks.
1. Which of the following blocks are used for error handling in SQL Server? Explanation: SQL Server 2005 introduced TRY… CATCH statement which helps us to handle the errors effectively in the back end.
In SQL Server, you can use GOTO to alter the flow of execution. You can use it to “jump” to another part in the T-SQL code. The way it works is, you create a label, then you can use GOTO to jump to that label. Any code between GOTO and the label are skipped, and processing continues at the label.
According to the Differences Between RAISERROR and THROW in Sql Server: Both RAISERROR and THROW statements are used to raise an error in Sql Server. The journey of RAISERROR started from Sql Server 7.0; whereas the journey of the THROW statement has just begun with Sql Server 2012.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With