Mr.Park
Mr.Park

Reputation: 123

mariadb IF statements error message?

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.

Upvotes: 9

Views: 12606

Answers (2)

elenst
elenst

Reputation: 3987

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');

Upvotes: 14

DavidX
DavidX

Reputation: 1319

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

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

Upvotes: -1

Related Questions