Recover a failed transaction safely
Use `SET XACT_ABORT`, `TRY...CATCH`, `XACT_STATE`, and rollback to leave a failed unit of work in a known state.
What you are trying to do
A batch updates a temporary account table and violates a local check constraint. Run this self-contained failure drill in one SQL Server session. It does not touch permanent tables.
Work through it
- Read the CHECK constraint before running the update. The script deliberately sets a balance below zero to produce a run-time constraint error.
- Inspect
ERROR_NUMBER,ERROR_MESSAGE, andXACT_STATEinside CATCH. WithXACT_ABORT ON, the failed transaction is uncommittable and must be rolled back. - Read the row after CATCH. It should retain its starting balance because the transaction was rolled back.
- Change the update to a valid balance and repeat. Compare the success path with the caught error path.
- Keep transaction ownership clear in stored procedures. A nested
BEGIN TRANSACTIONdoes not create an independently committable transaction. Review Microsoft's TRY/CATCH and XACT_ABORT rules. TRY...CATCH · XACT_ABORT
Check your work
The catch output reports the constraint error and an uncommittable transaction state before rollback. The final SELECT returns balance 100. The temporary table is dropped and XACT_ABORT is turned off for the rest of the session.
Practice SQL
Open in SQL FlowSET XACT_ABORT ON;
CREATE TABLE #LabBalance (AccountId int NOT NULL PRIMARY KEY, Balance int NOT NULL CHECK (Balance >= 0));
INSERT INTO #LabBalance (AccountId, Balance) VALUES (1, 100);
BEGIN TRY
BEGIN TRANSACTION;
UPDATE #LabBalance SET Balance = -1 WHERE AccountId = 1;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage, XACT_STATE() AS TransactionState;
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
END CATCH;
SELECT AccountId, Balance FROM #LabBalance;
DROP TABLE #LabBalance;
SET XACT_ABORT OFF;
Knowledge check
Commands in this lesson
Next lesson Build and prove a point-in-time restore plan