Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollback and Raiseerror, which first?

I sometimes perform the following set of statement in the following order:

Raiseerror(...)
Rollback;

but I am wondering if it cause the same effect as below:

Rollback;
Raiseerror(...)

I understand they are the same and cause the same effect. Doing Rollback first, after execution it continues executing on the following line, that is, Raiseerrror(...)

Could anyone confirm this? or is preferable to execute this set of statements in a concret way?

like image 656
Ralph Avatar asked Nov 19 '16 09:11

Ralph


People also ask

Can we rollback after delete?

DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.

What happens after rollback?

ROLLBACK undo the changes made by the current transaction. 2. The transaction can not undo changes after COMMIT execution. Transaction reaches its previous state after ROLLBACK.

Does rollback abort transaction?

ABORT rolls back the current transaction and causes all the updates made by the transaction to be discarded. This command is identical in behavior to the standard SQL command ROLLBACK , and is present only for historical reasons.

Can we rollback without begin?

Once SQL Server commits a transaction, you cannot run the ROLLBACK statement. Each rollback statement should have an association with the BEGIN Transaction statement.


1 Answers

It would matter if you were in a TRY-CATCH block - the raiserror would divert execution to the catch block, so if the rollback came after it (within the try block) then it would not execute.

Also it would depend on the severity of the error - severity 20+ terminates the database connection.

A nice pattern to use is something like

begin try
    begin transaction;

    -- do stuff

    commit transaction;
end try
begin catch
    declare @ErrorMessage nvarchar(max), 
        @ErrorSeverity int, 
        @ErrorState int;

    select @ErrorMessage = ERROR_MESSAGE() + ' Line ' + cast(ERROR_LINE() as nvarchar(5)), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE();

    if @@trancount > 0
        rollback transaction;

    raiserror (@ErrorMessage, @ErrorSeverity, @ErrorState);
end catch
like image 127
James Casey Avatar answered Oct 19 '22 23:10

James Casey