I would like to write a SQL script that executes multiple individual SQL statements; if any of those statements fail, I'd like to rollback the entire transaction. So, something like:
BEGIN TRANSACTION
insert into TestTable values (1)
insert into TestTable values (2)
insert into TestTabe values (3)
--if any of the statements fail
ROLLBACK
--else
COMMIT
This is for MS SQL 2008. Is there anything I can do to accomplish this? Perhaps some kind of exception handling?
I realize in my example I could inspect the TestTable for these values and determine if the statements failed that way. But in reality my SQL will be much more complex and I'd rather abstract myself from knowing what the SQL was doing.
SQL Server has had exception support since 2005:
BEGIN TRY
BEGIN TRAN
INSERT INTO ...
COMMIT TRAN
END TRY
BEGIN CATCH
EXECUTE usp_LogAndRethrowError
END CATCH
Your LogAndRethrowError can then roll back any doomed transactions, a la:
-- Make sure we are not in a live or 'doomed' transaction
IF XACT_STATE() <> 0
ROLLBACK TRANSACTION
This is one way I have done this in the past:
Declare @HasError int;
set @HasError = 0;
BEGIN TRANSACTION
insert into TestTable values (1)
if (@@ERROR != 0)
set @HasError = 1
insert into TestTable values (2)
if (@@ERROR != 0)
set @HasError = 1
insert into TestTabe values (3)
if (@@ERROR != 0)
set @HasError = 1
if @HasError > 0
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With