Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolling back the whole procedure (all statements)

Tags:

sql-server

How can I write the procedure in a way so that I can ROLLBACK all the INSERT, UPDATE and DELETE statements whenever ANY statement in it had an error.

Please note that my procedure might and might not have statements listed in sequence. In other words, I have an INSERT statements, then some IF logic, then a select statement, then another INSERT, then an UPDATE, followed by logic then DELETE statement, etc.

I just want to ROLLBACK all the INSERT, UPDATE and DELETE statements if error happened for any statement. I found this code http://msdn.microsoft.com/en-us/library/ms181299.aspx and http://en.allexperts.com/q/MS-SQL-Server-1801/Rollback-SP.htm

But they don't answer my question.

like image 816
JoHa Avatar asked Aug 07 '10 13:08

JoHa


People also ask

Can update statement be rolled back?

By wrapping your SQL INSERT UPDATE or DELETE statement in a TRANSACTION you have the ability to ROLLBACK or COMMIT your changes.

What is rolling back in database?

In database technologies, a rollback is an operation which returns the database to some previous state. Rollbacks are important for database integrity, because they mean that the database can be restored to a clean copy even after erroneous operations are performed.

What is the effect of rollback statement?

The rollback statement undoes part or all of the current transaction. If you omit the to savepointname clause, the statement terminates the transaction and rolls back any changes made by the transaction.


2 Answers

If the transaction is running with XACT_ABORT option on this will happen automatically.

set xact_abort on
begin tran

/*Your code*/


commit

Here's quite an interesting question discussing using this vs structured error handling.

like image 127
Martin Smith Avatar answered Oct 06 '22 11:10

Martin Smith


Check out how TRANSACTION works (the link you give also uses it, but there transaction seems bugged due to DTS interaction). Basically you can roll back everything you did since you signalled that you're starting your transaction.

Martin Smith's answer with xact_abort is desribed in more detail here.

like image 25
Tobiasopdenbrouw Avatar answered Oct 06 '22 11:10

Tobiasopdenbrouw