简体   繁体   中英

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 :

  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 :

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

I have tried IF..THEN..ENDIF and I got same error

How can I do that without using Stored Procedures and Parameters ?!

I`m Using UniDAC and Delphi XE6 and MySQL(InnoDB)

thanks ...

Use local variable to store the result of the count query and then use the variable in the if condition.

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; that you must put at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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