IF syntax error

2019-06-23 07:30发布

问题:

I'm getting a syntax error while following the MySQL guide for IF syntax.

My query is:

if 0=0 then select 'hello world'; end if;

Logically, this should select 'hello world', but instead I get

ERROR 1064 (42000): 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 (0=0) then select 'hello world'' at line 1
ERROR 1064 (42000): 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 'end if' at line 1

回答1:

Your query is only valid in a stored procedure/function context. See there for reference.



回答2:

using if statements like this is valid only inside stored procedure or functions.

What you'd probably like to use is the if() function, and then you can use:

select IF(0=0, 'hello world','');


回答3:

If statements are not supported in general SQL flow. It can only be used in functions or procedures. However you can use it in following way

use my_db;
delimiter #
create procedure xyz()
 begin
   IF 0=0 then select 'hello world';
 end if;
end#