Transactions and concurrency
TRY/CATCH and XACT_STATE for safe error handling
Inspect transaction state after a deliberate duplicate-key error on a temp table.
Lesson 70 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Inspect transaction state after a deliberate duplicate-key error on a temp table. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
CREATE TABLE #Keys (ID int NOT NULL PRIMARY KEY);
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO #Keys VALUES (1);
INSERT INTO #Keys VALUES (1);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
DECLARE @StateInCatch int = XACT_STATE();
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
SELECT @StateInCatch AS StateInCatch, XACT_STATE() AS StateAfterRollback;
END CATCH;
DROP TABLE #Keys;
SET XACT_ABORT OFF;Read it step by step
- The second INSERT violates the temp table primary key and transfers control to CATCH.
- XACT_STATE reports whether the transaction is active and committable; with XACT_ABORT ON this error makes it uncommittable.
- The CATCH rolls back before reporting state 0 afterward.
Check the result
| StateInCatch | StateAfterRollback |
|---|---|
| -1 | 0 |
The deliberate error is handled; no canonical row is touched.
Practice
Repeat with an attempted duplicate ID 2 and report the same two transaction states.
Check your answer and expected result
Reveal answer
CREATE TABLE #Keys (ID int NOT NULL PRIMARY KEY);
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO #Keys VALUES (2);
INSERT INTO #Keys VALUES (2);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
DECLARE @StateInCatch int = XACT_STATE();
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
SELECT @StateInCatch AS StateInCatch, XACT_STATE() AS StateAfterRollback;
END CATCH;
DROP TABLE #Keys;
SET XACT_ABORT OFF;| StateInCatch | StateAfterRollback |
|---|---|
| -1 | 0 |
The duplicate key sends execution to CATCH; rollback clears the transaction.
Your progress
Reveal the check answer or reach the end to complete this lesson.