Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query that'll rollback if any statements fails

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.

like image 618
reustmd Avatar asked Dec 14 '22 00:12

reustmd


2 Answers

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
like image 112
Rowland Shaw Avatar answered Dec 15 '22 14:12

Rowland Shaw


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
like image 26
Brettski Avatar answered Dec 15 '22 13:12

Brettski