简体   繁体   中英

Simple IF Statement in MySQL isn't working

I have a table with columns id and name .

START TRANSACTION;
UPDATE Test SET name='test' where id=1;
SELECT ROW_COUNT() INTO @affected_rows;
IF (@affected_rows > 0) THEN
    COMMIT;
ELSE
    ROLLBACK;
END IF

It seems to be returning an error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (affected_rows > 0) THEN COMMIT' at line 1 0 secs

Currently running MySQL 5.6.22

First, if as a control flow expression is only allowed in programming blocks -- stored procedures, triggers, and functions.

Second, the logic doesn't make sense. If no rows are affected, there is no need to rollback the transaction.

To point out the documentation :

The IF statement for stored programs implements a basic conditional construct.

The term "stored programs" means some programming block. Don't confuse this if with the MySQL function if() , which can be used in a query.

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