IF构造在MySql中产生错误#1064

时间:2022-06-19 20:21:01

I am attempting to run the following code in phpMyAdmin:

我试图在phpMyAdmin中运行以下代码:

set @tagTokenNum=0;
select @tagTokenNum:=tag_token_id from tag_token where tag_token_name = 'XXX';
delimiter go
if @tagTokenNum is null then 
   insert into tag_token (tag_token_name) values ('XXX');
   select @tagTokenNum:=last_insert_id();
end if;
go

I have also tried this without the delimiter statement and corresponding go. I receive the error message "#1064 - 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 @tagTokenNum is null then insert into tag_token ..."

我也尝试了这个没有分隔符语句和相应的go。我收到错误消息“#1064 - 您的SQL语法中有错误;请查看与您的MySQL服务器版本对应的手册,以便在@tagTokenNum为null后使用正确的语法,然后插入到tag_token ......”

As far as I can tell, I am following proper syntax for IF statements in MySql. I'm much more familiar with Microsoft SQL, so it's entirely possible I'm doing something wrong. I'd appreciate any help you can offer. Thanks. - Dave

据我所知,我在MySql中遵循IF语句的正确语法。我对Microsoft SQL更熟悉,所以我完全有可能做错了。我很感激您提供的任何帮助。谢谢。 - 戴夫

1 个解决方案

#1


2  

ISTR that you can only use if statements in stored procedures, ref: mysql docs ...An IF ... END IF block, like all other flow-control blocks used within stored programs....

ISTR你只能在存储过程中使用if语句,ref:mysql docs ...一个IF ... END IF块,就像存储程序中使用的所有其他流控制块一样....

However I think that you could achieve the same with the following:

但是我认为您可以通过以下方式实现相同目标:

insert into tag_token (tag_token_name) values ('XXX')
    ON DUPLICATE KEY UPDATE tag_token_name = tag_token_name;

select @tagTokenNum:=tag_token_id from tag_token where tag_token_name = 'XXX'

#1


2  

ISTR that you can only use if statements in stored procedures, ref: mysql docs ...An IF ... END IF block, like all other flow-control blocks used within stored programs....

ISTR你只能在存储过程中使用if语句,ref:mysql docs ...一个IF ... END IF块,就像存储程序中使用的所有其他流控制块一样....

However I think that you could achieve the same with the following:

但是我认为您可以通过以下方式实现相同目标:

insert into tag_token (tag_token_name) values ('XXX')
    ON DUPLICATE KEY UPDATE tag_token_name = tag_token_name;

select @tagTokenNum:=tag_token_id from tag_token where tag_token_name = 'XXX'