Lesson 2 of 2 Error Handling in T-SQL

Transactions, XACT_ABORT and Retry Logic

This lesson explains how XACT_ABORT and XACT_STATE keep transactions consistent when errors occur, how nested transactions behave and how to retry transient errors.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain the effect of SET XACT_ABORT ON.
  • Interpret the values returned by XACT_STATE().
  • Describe a safe retry pattern for deadlocks and transient errors.

XACT_ABORT and transaction state

By default, many runtime errors, such as a constraint violation, abort only the failing statement, and the transaction continues with the earlier statements applied. SET XACT_ABORT ON makes most runtime errors roll back the entire transaction and stop the batch, which is the safe default for procedures that modify data; it also ensures that a client timeout, which cancels the batch, does not leave a transaction open.

Inside CATCH, XACT_STATE() reports the transaction's state: 1 means a committable transaction is open, -1 means it is uncommittable (doomed) and can only be rolled back, and 0 means no transaction is open. @@TRANCOUNT counts nested BEGIN TRANSACTION statements but does not say whether the transaction can commit.

The following diagram compares the same failing transaction with XACT_ABORT off and on.

The effect of XACT_ABORT. By default, many runtime errors abort only the failing statement, and the transaction continues with earlier statements applied. With SET XACT_ABORT ON, most runtime errors roll back the whole transaction and stop the batch, and a client timeout that cancels the batch does not leave a transaction open holding locks. Inside CATCH, XACT_STATE() reports 1 for committable, -1 for doomed and 0 for no transaction.
Set XACT_ABORT ON in procedures that modify data.
Match the pairs

Transaction state

Exam skills 1.3.8

Match each value or setting with its meaning.

Log in to try this activity Interactive activities are free with an account.

A standard pattern

CREATE OR ALTER PROCEDURE Sales.usp_TransferStock
    @FromWarehouse int, @ToWarehouse int, @ProductID int, @Qty int
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    BEGIN TRY
        BEGIN TRANSACTION;
            UPDATE Inventory.Stock SET OnHand -= @Qty
            WHERE WarehouseID = @FromWarehouse AND ProductID = @ProductID AND OnHand >= @Qty;
            IF @@ROWCOUNT = 0 THROW 50020, N'Insufficient stock.', 1;
            UPDATE Inventory.Stock SET OnHand += @Qty
            WHERE WarehouseID = @ToWarehouse AND ProductID = @ProductID;
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
        THROW;
    END CATCH;
END;

Nested BEGIN TRANSACTION statements only increment @@TRANCOUNT: the inner COMMIT decrements it, and only the outermost COMMIT makes changes durable, while any ROLLBACK (without a savepoint name) rolls back everything. SAVE TRANSACTION name creates a savepoint for partial rollback when the transaction is still committable.

Spot the bug

A transfer that half-completes

Exam skills 1.3.8

Find the lines that can leave stock moved in only one warehouse.

Log in to try this activity Interactive activities are free with an account.

Retrying transient errors

Some errors succeed when retried: deadlock victim 1205, snapshot update conflict 3960, and in Azure SQL Database transient connectivity and throttling errors such as 40501, 40613 and 49918. Retries can be implemented in T-SQL with a loop around TRY...CATCH or, more commonly, in the application's data access layer, which also handles dropped connections. The following steps describe a safe retry loop.

  1. Wrap the unit of work

    Put the whole transaction inside TRY, with XACT_ABORT ON.

  2. Classify the error

    In CATCH, roll back if XACT_STATE() is not 0, then check ERROR_NUMBER() against the list of transient errors.

  3. Back off and retry

    For a transient error, wait with WAITFOR DELAY (increasing each time) and retry up to a fixed number of attempts.

  4. Give up loudly

    For other errors, or after the last attempt, re-raise with THROW so the caller sees the failure.

Sort into groups

Retry or give up?

Exam skills 1.3.8

Decide whether each error is worth retrying.

Log in to try this activity Interactive activities are free with an account.
Worked example

An open transaction after a timeout

An application's command timeout cancels a long-running procedure call. Afterwards, other sessions are blocked by the timed-out session, which shows an open transaction while sleeping. The procedure uses TRY...CATCH but not XACT_ABORT. What should the developer add?

Add SET XACT_ABORT ON at the start of the procedure. A client timeout sends an attention signal that stops the batch without running the CATCH block, so the transaction remains open and holds its locks until the connection is reused or closed. With XACT_ABORT ON, the transaction is rolled back when the batch is cancelled. Increasing the timeout only delays the problem, and the CATCH block never runs in this case.

Check yourself

Does a client command timeout run the procedure's CATCH block?

Show answer

No. The attention signal stops the batch, so the transaction stays open unless SET XACT_ABORT ON is used.

Exam Tips

Remember for the exam

  • Procedures that modify data: SET XACT_ABORT ON.
  • XACT_STATE() = -1: roll back, the transaction cannot commit.
  • Only the outermost COMMIT makes nested transactions durable; ROLLBACK undoes everything.
  • Retry 1205 deadlocks and transient Azure SQL errors with backoff and a limit.