简体   繁体   English

MySQL:如果条件为真,则启动事务

[英]MySQL : start Transaction if a condition was true

I want to execute some runtime-generated SQL commands in a Transaction, there is no problem, but I should start this transaction if a condition was true, for example : 我想在事务中执行一些运行时生成的SQL命令,没有问题,但是如果条件为真,则应该启动该事务,例如:

  SQLText := 'IF (SELECT COUNT(ID) FROM desk_table WHERE Status = 1 AND Number = ' 
           + IndDeskGrid.DataSource.DataSet.FieldByName('Number').AsString + ' > 0) BEGIN '
           + 'SET autocommit = 0;'
           + 'START TRANSACTION;'
           + 'INSERT INTO waiting_table (UName, DNumber, MDate, HDate, HaveReq)'
           + ' VALUES (' + QuotedStr(User.UName) + ', ' 
           + IndDeskGrid.DataSource.DataSet.FieldByName('Number').AsString
           + ', ' + QuotedStr(MTodayString) + ', ' + QuotedStr(HTodayString) + ', 2);'
           + 'UPDATE desk_table SET Status = 2 WHERE Number = ' 
           + IndDeskGrid.DataSource.DataSet.FieldByName('Number').AsString + ';'
           + 'COMMIT;'
           + 'SET autocommit = 1;'
           + 'END;';

Generated SQL : 生成的SQL:

IF (SELECT COUNT(ID) FROM desk_table WHERE Status = 1 AND Number = 202 > 0)
BEGIN
SET autocommit = 0;
START TRANSACTION;
INSERT INTO waiting_table (UName, DNumber, MDate, HDate, HaveReq)
VALUES ('UserName', 202, '2015/09/25', '2015/09/25', 2);
UPDATE desk_table SET Status = 2 WHERE Number = 202;
COMMIT;
SET autocommit = 1;
END;

but when I use IF like above code , I got syntax error 但是当我像上面的代码一样使用IF时,出现语法错误

I have tried IF..THEN..ENDIF and I got same error 我已经尝试过IF..THEN..ENDIF,但遇到了相同的错误

How can I do that without using Stored Procedures and Parameters ?! 不使用存储过程和参数怎么办?

I`m Using UniDAC and Delphi XE6 and MySQL(InnoDB) 我使用UniDAC和Delphi XE6和MySQL(InnoDB)

thanks ... 谢谢 ...

Use local variable to store the result of the count query and then use the variable in the if condition. 使用局部变量存储计数查询的结果,然后在if条件中使用该变量。

declare @total int
SELECT @total = COUNT(ID) FROM desk_table WHERE Status = 1 AND Number = 202;
IF (@total > 0)
BEGIN
SET autocommit = 0;
START TRANSACTION;
INSERT INTO waiting_table (UName, DNumber, MDate, HDate, HaveReq)
VALUES ('UserName', 202, '2015/09/25', '2015/09/25', 2);
UPDATE desk_table SET Status = 2 WHERE Number = 202;
COMMIT;
SET autocommit = 1;
END;

acutaly it's end if; 如果这样,它就end if; that you must put at the end 必须放在最后

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

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