Is possible to do a ROLLBACK in a MySQL trigger?

痴心易碎 提交于 2020-01-11 06:23:33

问题


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

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


回答1:


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




回答2:


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 ;



回答3:


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.



来源:https://stackoverflow.com/questions/6634093/is-possible-to-do-a-rollback-in-a-mysql-trigger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!