MTK
MTK

Reputation: 3580

if elseif conditions in mysql query

due to lack of SUPER privileges in hosting, I need to convert some stored procedures to SQL queries. I tried:

SET @condition = 0;

IF (@condition = 0) THEN
   SELECT 'IF result' AS res;
ELSEIF (@condition = 1) THEN
   SELECT 'ELSEIF result' AS res;   
ELSE
   SELECT 'ELSE result' AS res;
END IF;

But I got sintax error:

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 'ELSEIF (@condition = 1) THEN SELECT 'ELSEIF result' AS res' at line 1

Upvotes: 1

Views: 1396

Answers (2)

flyingfox
flyingfox

Reputation: 13506

You can try with below:

 SELECT  CASE 
            WHEN @condition=1 THEN 'if result'
            WHEN @condition=0 THEN 'elseif result'
            ELSE 'else result'
            END AS res;

Upvotes: 2

Mohamed Sakeel
Mohamed Sakeel

Reputation: 36

Try using CASE ELSE END Maybe the SQL confuses with the IF statement being a string in the quotation mark

CASE
    WHEN search_condition THEN statement_list
    [WHEN search_condition THEN statement_list] ...
    [ELSE statement_list]
END CASE

Upvotes: 1

Related Questions