0

I am providing 4 examples below. My question is - which is the appropriate template to use when dealing with try/catch and transactions.

Example 1

TSQL Try / Catch within Transaction or vice versa?

The accepted answer for the above has the following structure:

BEGIN TRY    
  BEGIN TRANSACTION SCHEDULEDELETE
    // do something
  COMMIT TRANSACTION SCHEDULEDELETE
  PRINT 'Operation Successful.'
END TRY

BEGIN CATCH 
  IF (@@TRANCOUNT > 0)
   BEGIN
      ROLLBACK TRANSACTION SCHEDULEDELETE
      PRINT 'Error detected, all changes reversed'
   END 
    //may be print/log/throw error
END CATCH 

Example 2

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-ver15#b-using-trycatch-in-a-transaction

The structure given is:

BEGIN TRANSACTION;  
BEGIN TRY  
    -- Generate a constraint violation error.  
    DELETE FROM Production.Product  
    WHERE ProductID = 980;  
END TRY  
BEGIN CATCH  
    //may be print/log/throw error
  
    IF @@TRANCOUNT > 0  
        ROLLBACK TRANSACTION;  
END CATCH;  
  
IF @@TRANCOUNT > 0  
    COMMIT TRANSACTION;  
GO  

Example 3

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-ver15#c-using-trycatch-with-xact_state

Microsoft also recommends using XACT_ABORT.

SET XACT_ABORT ON;  
  
BEGIN TRY  
    BEGIN TRANSACTION;  
    //do something    
    COMMIT TRANSACTION;  
END TRY  
BEGIN CATCH  
    -- Test whether the transaction is uncommittable.  
    IF (XACT_STATE()) = -1  
    BEGIN  
        PRINT  
            N'The transaction is in an uncommittable state.' +  
            'Rolling back transaction.'  
        ROLLBACK TRANSACTION;  
    END;  
  
    -- Test whether the transaction is committable.
    -- You may want to commit a transaction in a catch block if 
    -- you want to commit changes to statements that ran prior 
    -- to the error.
    IF (XACT_STATE()) = 1  
    BEGIN  
        PRINT  
            N'The transaction is committable.' +  
            'Committing transaction.'  
        COMMIT TRANSACTION;     
    END;  
END CATCH;  

Example 4

This is what I use personally

BEGIN TRY
  BEGIN TRANSACTION
    //do something    
  COMMIT TRANSACTION
END TRY

BEGIN CATCH
  IF (@@TRANCOUNT > 0)
  BEGIN
   ROLLBACK TRANSACTION
  END ;

  //may be print/log/throw error

END CATCH

To summarize:

  1. Example 1 - Transaction is inside the try block
  2. Example 2 - Try is inside the transaction block, COMMIT is after the catch block
  3. Example 3 - Transaction is inside the try block with xact_abort ON functionality
  4. Example 4 - Transaction is inside the try block, COMMIT is inside and as the last line of the try block

Is my approach (example 4) the correct way to handle try/catch and transaction in SQL. If not, then why not and which example should I use to refactor my code from example 4?

variable
  • 8,262
  • 9
  • 95
  • 215
  • I suggest your option 4 with slight modifications. `BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK; THROW; END CATCH` and add `SET XACT_ABORT_ON;` to ensure transactions are immediately rolled back even when the catch block is not executed (e.g. due to a client query timeout). – Dan Guzman Jan 27 '22 at 10:50
  • 1
    I'd suggest you don't catch at all, instead just use `XACT_ABORT ON`. Let the client catch errors. See also https://stackoverflow.com/a/70185323/14868997 – Charlieface Jan 27 '22 at 10:55
  • Certainly you should NEVER eat an error and convert into a resultset. Nor should you use PRINT to provide useful or important information to the caller of a sql batch. The MS documentation does have a bad habit of using crap code - but that is usually just for demonstration purposes and it is not suggested as good practices or habits. Read Erland's discussion of [error handling](https://www.sommarskog.se/error_handling/Part1.html) – SMor Jan 27 '22 at 12:56
  • Can someone give a standard template in the answer section. – variable Jan 27 '22 at 13:10
  • @Charlieface - the link that you have provided - the catch block does an INSERT followed by ROLLBACK, so wont the rollback undo the insert? – variable Feb 01 '22 at 05:15
  • @DanGuzman - 1. Effectively, you are saying that adding `SET XACT_ABORT_ON` is the only addition required to my sample (example 4)? 2. Does XACT_ABORT rollback upon only those errors that TRY block doesn't or does it rollback upon any error? If its the later (rollback for all errors), then does it prevent errors from hitting the CATCH block? – variable Feb 01 '22 at 05:38
  • It rolls back pretty much everything even without a `TRY` `CATCH`, there are a couple of weird edge cases that Erland Sommarskog notes, but they are not really relevant – Charlieface Feb 01 '22 at 09:18
  • @variable, adding the what Charlieface mentioned, the addition of `SET XACT_ABORT ON` adheres to Erland's [General Pattern for Error Handling](https://www.sommarskog.se/error_handling/Part1.html#jumpgeneralpattern). – Dan Guzman Feb 01 '22 at 10:22

1 Answers1

1

according to the documentation

TRY...CATCH constructs do not trap the following conditions:

  • Warnings or informational messages that have a severity of 10 or lower.

  • Errors that have a severity of 20 or higher that stop the SQL Server Database Engine task processing for the session. If an error occurs that has severity of 20 or higher and the database connection is not disrupted, TRY...CATCH will handle the error.

  • Attentions, such as client-interrupt requests or broken client connections.

  • When the session is ended by a system administrator by using the KILL statement.

The following types of errors are not handled by a CATCH block when they occur at the same level of execution as the TRY...CATCH construct:

  • Compile errors, such as syntax errors, that prevent a batch from running.

  • Errors that occur during statement-level recompilation, such as object name resolution errors that occur after compilation because of deferred name resolution.

  • Object name resolution errors

These errors are returned to the level that ran the batch, stored procedure, or trigger.

so taking this fact into account, let's consider this examples.

Exaple 1: If we try to delete a row from a non-existent table, the session will remain with an open transaction, which will preserve resource locks and prevent VLFs from being reused in the transaction log for a simple recovery model.

BEGIN TRY    
  BEGIN TRANSACTION SCHEDULEDELETE
    Delete From dbo.NoExists Where ID=1
  COMMIT TRANSACTION SCHEDULEDELETE
END TRY

BEGIN CATCH 
  IF (@@TRANCOUNT > 0)
   BEGIN
      ROLLBACK TRANSACTION SCHEDULEDELETE
   END 
END CATCH

Invalid object name "dbo.NoExists".

Select @@TRANCOUNT
-- 1

Example 2: The same problem as in example 1.

BEGIN TRANSACTION;  
BEGIN TRY  
    DELETE FROM dbo.NoExists Where ID=1  
END TRY  
BEGIN CATCH    
    IF @@TRANCOUNT > 0  
        ROLLBACK TRANSACTION;  
END CATCH;  

IF @@TRANCOUNT > 0  
    COMMIT TRANSACTION;  

Invalid object name "dbo.NoExists".

Select @@TRANCOUNT
-- 1

Example 3: In this example, XACT_ABORT ON will rollback the transaction if CATCH block doesn't handle this error and, therefore, doesn't rollback the transaction.

SET XACT_ABORT ON;  

BEGIN TRY  
    BEGIN TRANSACTION;  
        DELETE FROM dbo.NoExists Where ID=1   
    COMMIT TRANSACTION;  
END TRY  
BEGIN CATCH  
    -- Test whether the transaction is uncommittable.  
    IF (XACT_STATE()) = -1  
    BEGIN  
        PRINT  
            N'The transaction is in an uncommittable state.' +  
            'Rolling back transaction.'  
        ROLLBACK TRANSACTION;  
    END;  

    IF (XACT_STATE()) = 1  
    BEGIN  
        PRINT  
            N'The transaction is committable.' +  
            'Committing transaction.'  
        COMMIT TRANSACTION;     
    END;  
END CATCH;

Invalid object name "dbo.NoExists".

Select @@TRANCOUNT
-- 0
Anton Grig
  • 1,640
  • 7
  • 11
  • So you are saying that example 3 is the correct template? I doubt it because - suppose your TRY block executes a stored procedure (which has its own try/catch/transaction block) and assume there is an error in the SP, thereby it will execute rollback and `throw`. When control enters the CATCH block of your example, then it does not check from @@TRANCOUNT - so will that not give an error because the transaction is already rolled back by the nested stored proc. – variable Jan 27 '22 at 14:09
  • @variable have you tried to reproduce this case? check out this [post](https://stackoverflow.com/questions/69583951/mysterious-error-after-exec-into-insert-into-from-stored-procedure-when-subord/69601197#69601197) perhaps this is the case you are asking about. – Anton Grig Jan 27 '22 at 15:05