简体   繁体   English

有条件地在没有存储过程的情况下在MySQL上提交事务

[英]Conditionally commit transactions on MySQL without stored procedure

I found their document said that the IF ELSE END IF is only supported in stored procedure. 我发现他们的文件说IF ELSE END IF仅在存储过程中受支持。

MySQL supports the IF, CASE, ITERATE, LEAVE LOOP, WHILE, and REPEAT constructs for flow control within **stored programs**.

We tried and seem that it is not supported in running batch statements via cli. 我们尝试过,似乎通过cli运行批处理语句不支持它。

To optimize the performance and reduce round trip, reading the ROW_COUNT() by an application is not considered. 为了优化性能并减少往返行程,不考虑由应用程序读取ROW_COUNT()。 The best if mysql can take it in the speed of light. 最好的办法是mysql能以光速运行。

How do I make it work without using any additional stored procedure? 如何在不使用任何其他存储过程的情况下使其工作? We tried to use WHERE ROW_COUNT() on every UPDATE to suspend the chain of updates if any one goes wrong; 如果有任何错误,我们尝试在每个UPDATE上使用W​​HERE ROW_COUNT()挂起更新链。 but it wont stop the transaction begin replicated even if nothing should be modified. 但是即使没有任何修改,它也不会停止事务开始复制。

EDIT: 编辑:

In short, how do I do 简而言之,我该怎么办

START TRANSACTION
UPDATE `table_a` SET a=1 WHERE id=1 AND addition=2;
UPDATE `table_b` SET a=1 WHERE id=1 AND another_rule=3;
IF UPDATE_COUNT() = 1 
THEN 
  COMMIT
ELSE
  ROLLBACK
END IF

In a crond schedule, without using stored procedure. 在crond计划中,不使用存储过程。

a work around if you don't want to use a stored procedure. 如果您不想使用存储过程,请变通解决。 it works fine for me 这对我来说可以

SET autocommit=0;
UPDATE table_a SET a=1 WHERE id=1 AND addition=2;
UPDATE table_b SET a=1 WHERE id=1 AND another_rule=3;
SET autocommit=IF(UPDATE_COUNT()=1,1,2);

autocommit will set to be 2 if not UPDATE_COUNT() = 1 and this will throw an exception 如果不是UPDATE_COUNT() = 1 ,则autocommit将设置为2 ,这将引发异常
Variable 'autocommit' can't be set to the value of '2'
handle this exception and execute ROLLBACK; 处理此异常并执行ROLLBACK;

I don't think what you want to do is possible, as is, without a stored procedure. 我认为如果没有存储过程,您想做的事情是不可能的。 Why are you averse to using a stored procedure? 您为什么不喜欢使用存储过程? The only other way I can think of doing this atm, is to have a staging table that can trim your duplicates and then do your commit in one step. 我可以想到的另一种方法是拥有一个临时表,该临时表可以修剪您的重复项,然后一步完成提交。

Malks. 马尔克斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM