mariadb IF statements error message?
Asked Answered
B

2

9

I test sql querys.

    IF 3 = 3 THEN 
       SELECT 'TRUE'
    ELSE
       SELECT 'FALSE'
    END IF;

I excuted that query on SQLyog.

I got the error message below.

 You have an error in your SQL syntax; check the manual that corresponds to 
 your MariaDB server version for the right syntax to use near 'ELSE SELECT 
 'FALSE' END IF' at line 3

That query is very simple. I don't know why happen error message.

Blooming answered 27/1, 2018 at 3:35 Comment(0)
S
14

IF itself is not a query, it cannot be executed as a standalone statement.

There are two different IFs that you can use.

One is the conditional construct in compound statements. It can be used in stored routines:

DELIMITER $
CREATE PROCEDURE pr()
BEGIN
    IF 3 = 3 THEN 
       SELECT 'TRUE';
    ELSE
       SELECT 'FALSE';
    END IF;
END $
DELIMITER ;
CALL pr;

Or, if you are running a reasonably new version of MariaDB (10.1+), you can also use it in an anonymous block:

DELIMITER $
BEGIN NOT ATOMIC
    IF 3 = 3 THEN 
       SELECT 'TRUE';
    ELSE
       SELECT 'FALSE';
    END IF;
END $
DELIMITER ;

Another is the IF function, which can be used inside a query:

SELECT IF(3 = 3 THEN 'TRUE','FALSE');
Seashore answered 28/1, 2018 at 13:35 Comment(0)
A
-1

You need semicolons at the end of each inner statement like so:

IF 3 = 3 THEN 
   SELECT 'TRUE';
ELSE
   SELECT 'FALSE';
END IF;
Amado answered 27/1, 2018 at 4:23 Comment(1)
SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2Discount

© 2022 - 2024 — McMap. All rights reserved.