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

时间:2015-09-25 13:13:58

标签: mysql sql delphi transactions unidac

我想在Transaction中执行一些运行时生成的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;';

生成的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;

但是当我像上面的代码一样使用IF时,我得到了语法错误

我试过IF..THEN..ENDIF我得到了同样的错误

如何在不使用存储过程和参数的情况下执行此操作?!

我正在使用UniDAC和Delphi XE6和MySQL(InnoDB)

谢谢......

2 个答案:

答案 0 :(得分:0)

使用局部变量存储计数查询的结果,然后在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;

答案 1 :(得分:0)

acutaly它的end if;你必须放在最后