MySQL 脚本中的 IF

art*_*rxe 6 mysql sql-scripts

我有以下脚本:


use my_db;

if (2 < 3) then
    select 1;
end if;
Run Code Online (Sandbox Code Playgroud)

当我用命令执行此操作时:

mysql --user=myuser --password=mypassword < script.sql

我收到以下错误:

ERROR 1064 (42000) at line 3: 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 (2 < 3) then select 1' at line 1

有人能解释一下为什么会这样吗?从这里找到的 mysql 文档我认为它应该工作正常。

Wad*_* M. 3

如果您可以更改您的声明,我建议您这样做:

select if(2<3, 'true','false') as amount
Run Code Online (Sandbox Code Playgroud)

或者将您的代码包装在过程中:

create procedure my_procedure() 
begin
  if (2 < 3) then
      select 1;
  end if;
end;

-- Execute the procedure
call my_procedure();

-- Drop the procedure
drop procedure my_procedure;
Run Code Online (Sandbox Code Playgroud)