I have the following code in a db update script:
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 reports:
SQL Error (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 (@index1 = 0) then create index IX_Entries_EmailAddress on Entries (EmailAddr’ at line 1
All the syntax looks correct according to the MYSQL docs, what am I missing?
Edit: Got it, thanks to Ryan’s answer.
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;
And
IFstatement like that can’t be used in a regular script – it’s a MySQL compound statement. They can only be used in triggers, stored procedures, etc.In a regular script, you’d need to update the logic to not use the
IFconstruct, but rather some of the built-in functions such asIFNULL().