Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to do a ROLLBACK in a MySQL trigger?

Tags:

mysql

triggers

Just that is the question: is possible to do a ROLLBACK in a MySQL trigger?

If answer is yes, then, please, explain how.

like image 751
Ivan Avatar asked Jul 09 '11 10:07

Ivan


People also ask

Can you ROLLBACK in a trigger?

If a ROLLBACK TRANSACTION is issued in a trigger: All data modifications made to that point in the current transaction are rolled back, including any made by the trigger. The trigger continues executing any remaining statements after the ROLLBACK statement.

Is ROLLBACK possible in MySQL?

A COMMIT or ROLLBACK statement ends the current transaction and a new one starts. If a session that has autocommit disabled ends without explicitly committing the final transaction, MySQL rolls back that transaction.

What will happen when a ROLLBACK statement is executed inside a trigger?

When the rollback trigger is executed, Adaptive Server aborts the currently executing command and halts execution of the rest of the trigger.

How do I ROLLBACK MySQL after update?

To have possibility to ROLLBACK DML statements (like INSERT , UPDATE or DELETE queries) you should use transaction blocks: START TRANSACTION; UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6; -- and more DML queries COMMIT; -- or ROLLBACK; Since transaction was COMMIT ed it can not be rolled back.


3 Answers

I've found out that this functionnality exists since MySQL 5.5 and does not work in earlier releases.

The trigger does no rollback or commit. To initiate any rollback, you have to raise an exception. Thus your insert/update/delete command will abort. The rollback or commit action has to be raised around your SQL command.

To raise your exception, in your XXX's trigger (eg.) :

create trigger Trigger_XXX_BeforeInsert before insert on XXX
for each row begin

    if [Test]
    then

      SIGNAL sqlstate '45001' set message_text = "No way ! You cannot do this !";

    end if ;

end ;
like image 135
BartmanDilaw Avatar answered Oct 23 '22 12:10

BartmanDilaw


If the trigger raises an exception, that will abort the transaction, effectively rolling back. Will this work for you?

like image 31
Flimzy Avatar answered Oct 23 '22 12:10

Flimzy


From: http://dev.mysql.com/doc/refman/5.1/en/trigger-syntax.html

The trigger cannot use statements that explicitly or implicitly begin or end a transaction such as START TRANSACTION, COMMIT, or ROLLBACK.

and

For transactional tables, failure of a statement should cause rollback of all changes performed by the statement. Failure of a trigger causes the statement to fail, so trigger failure also causes rollback. For nontransactional tables, such rollback cannot be done, so although the statement fails, any changes performed prior to the point of the error remain in effect.

like image 21
Mchl Avatar answered Oct 23 '22 13:10

Mchl