Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: IF in stored procedure

I am just getting my feet wet with stored procedures. According to the tutorials that I have seen, this should be valid (MySQL 5.5):

CREATE PROCEDURE someFunction ( a VARCHAR(256),  b VARCHAR(256) )
    BEGIN
        DECLARE haveAllVariables INT;
        SET haveAllVariables = 1;

    IF     a = "" THEN SET haveAllVariables = 0
    ELSEIF b = "" THEN SET haveAllVariables = 0
    END IF;

However, it is throwing this 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 'ELSEI
F b = "" THEN SET haveAllVariables = 0

Where is the error in my syntax?

Thanks.

like image 956
dotancohen Avatar asked Mar 10 '12 20:03

dotancohen


People also ask

Can we use if else in stored procedure?

The IF ELSE statement controls the flow of execution in SQL Server. It can be used in stored-procedures, functions, triggers, etc. to execute the SQL statements based on the specified conditions.

Can I use if condition in MySQL query?

MySQL IF() FunctionThe IF() function returns a value if a condition is TRUE, or another value if a condition is FALSE.

How do I run an if statement in MySQL?

The syntax for the IF-THEN-ELSE statement in MySQL is: IF condition1 THEN {... statements to execute when condition1 is TRUE...} [ ELSEIF condition2 THEN {...


1 Answers

You're missing a semicolon

CREATE PROCEDURE someFunction ( a VARCHAR(256),  b VARCHAR(256) )
    BEGIN
        DECLARE haveAllVariables INT;
        SET haveAllVariables = 1;

    IF     a = "" THEN SET haveAllVariables = 0;
    ELSEIF b = "" THEN SET haveAllVariables = 0;
    END IF;
like image 70
Martin. Avatar answered Oct 14 '22 19:10

Martin.