Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Use XACT ABORT to roll back non trappable error transactions
From Wiki
Let's say you have a transaction and you want to make sure that it rolls back everything even when you have a non trappable error. What can you do? You can use XACT_ABORT and set it to on. First create this table
- CREATE TABLE LogError(ErrorID INT PRIMARY KEY)
- GO
Now run this transaction
- BEGIN TRANSACTION TranA
- DECLARE @error INT
- INSERT LogError VALUES(1)
- SELECT @error = @@ERROR
- IF @error =0
- BEGIN
- INSERT LogError VALUES(2)
- SELECT @error = @@ERROR
- END
- IF @error =0
- BEGIN
- INSERT LogError VALUES(3)
- SELECT @error = @@ERROR
- END
- --Will blow up here with a non trapable error
- IF @error =0
- BEGIN
- INSERT LogError2 VALUES(1)
- SELECT @error = @@ERROR
- END
- IF @error =0
- BEGIN
- COMMIT TRAN TranA
- END
- ELSE
- BEGIN
- ROLLBACK TRAN TranA
- END
So the transaction blew up with the following error
Server: Msg 208, Level 16, State 1, Line 22
Invalid object name 'LogError2'.
Now run this query
- SELECT * FROM LogError
That is right the first three inserts are in the table
Delete those rows
- DELETE LogError
If you set XACT_ABORT on before the transaction then everything will be rolled back
Run this block of code
- SET XACT_ABORT ON
- BEGIN TRANSACTION TranA
- DECLARE @error INT
- INSERT LogError VALUES(1)
- SELECT @error = @@ERROR
- IF @error =0
- BEGIN
- INSERT LogError VALUES(2)
- SELECT @error = @@ERROR
- END
- IF @error =0
- BEGIN
- INSERT LogError VALUES(3)
- SELECT @error = @@ERROR
- END
- --Will blow up here with a non trapable error
- IF @error =0
- BEGIN
- INSERT LogError2 VALUES(1)
- SELECT @error = @@ERROR
- END
- IF @error =0
- BEGIN
- COMMIT TRAN TranA
- END
- ELSE
- BEGIN
- ROLLBACK TRAN TranA
- END
Now run this query
- SELECT * FROM LogError
That is right no rows. Keep in mind that if you run the first query again in the same query window it will rollback the three rows also since the XACT_ABORT is still set to on, you have to run this
- SET XACT_ABORT OFF
To get the same behaviour like when you ran it first you can run the first transaction in another query window.
Applies to:
- SQL Server 2005 - SQL Server 2008
Contributed by: --SQLDenis 02:51, 31 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Handy tricks



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.