MySQL使用Create Index In If If语句报告语法错误



我在DB Update脚本中具有以下代码:

set @index1 = ifnull((select count(1) from information_schema.statistics
    where table_name = 'Entries' and index_name = 'IX_Entries_EmailAddress'),0);
set @index2 = ifnull((select count(1) from information_schema.statistics 
    where table_name = 'Entries' and index_name = 'IX_Entries_FirstLastName'),0);
if (@index1 = 0) then create index IX_Entries_EmailAddress on Entries (EmailAddress);
if (@index2 = 0) then create index IX_Entries_FirstLastName on Entries (FirstName, LastName); 

mysql报告:

SQL错误(1064):您的SQL语法中有一个错误;查看与您的MySQL Server版本相对应的手册,以获取右边的语法,以接近'if(@index1 = 0),然后在条目上创建index ix_entries_emailAddress(emailAddr'line 1

>

根据MySQL文档,所有语法看起来都正确,我缺少什么?

编辑:借助Ryan的答案。

set @sqlcmd := if(@index1 = 0, 'create index IX_Entries_EmailAddress on Entries (EmailAddress);', '');
prepare stmt from @sqlcmd;
execute stmt;
set @sqlcmd := if(@index2 = 0, 'create index IX_Entries_FirstLastName on Entries (FirstName, LastName);', '');
prepare stmt from @sqlcmd;
execute stmt;

IF语句类似的语句无法在常规脚本中使用 - 它是mySQL复合语句。它们只能用于触发器,存储过程等。

在常规脚本中,您需要更新逻辑以不使用IF构造,而是一些内置功能,例如IFNULL()

最新更新