Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad practice to use SQL Server's GOTO for error handling?

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?

like image 592
Abe Miessler Avatar asked Jun 21 '12 15:06

Abe Miessler


People also ask

How do you handle errors in SQL Server?

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.

Which of the following blocks are used for error handling in SQL Server?

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.

How do I use GOTO in SQL?

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.

What is the difference between Raiserror and throw?

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.


1 Answers

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
like image 102
SliverNinja - MSFT Avatar answered Nov 15 '22 19:11

SliverNinja - MSFT