Why won't simple If ELSE Statement work in mySql

眉间皱痕 提交于 2020-01-02 15:15:06

问题


I'm trying to create a simple stored procedure with an if else statement in SQLYog against a mySql db. I'm not overly familiar with mySql syntax so i'm hoping it's something simple but I just can't see why this isn't working

CREATE PROCEDURE p(IN Number INT)

IF NUMBER = 1 THEN
SELECT * FROM tblProduct WHERE ProductID = Number
ELSE SELECT * FROM tblProduct WHERE ProductId = 2
END IF

I'd appreciate if anyone can help me with this and tell me where i'm going wrong. Thanks for reading.

I get the following when I try to execute:

Error Code : 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 'ELSE SELECT * FROM tblProduct where intProductId = 2 END IF' at line 5


回答1:


Statements in MySQL are delimited by semicolons. To create procedures with them, you do a little trick like so:

DELIMITER //

CREATE PROCEDURE p(IN Number INT)
BEGIN
    IF NUMBER = 1 THEN
        SELECT * FROM tblProduct WHERE ProductID = Number;
    ELSE
        SELECT * FROM tblProduct WHERE ProductId = 2;
    END IF;
END //

DELIMITER ;

Check out the documentation for if/else for more info.




回答2:


You need a ; after your select statements. You also need BEGIN and END around your procedure body. See the manual for lots of examples about the exact syntax for procedures.




回答3:


Remember the IF ELSE statement is always used in stored procedure, triggers not in simple select query. And ELSE OR IF keyword always write in new line not in front of query.Like below

Correct syntax:

DELIMITER //

CREATE PROCEDURE NAME(IN Number INT)
BEGIN
    IF roll= 1 THEN
        SELECT * FROM table1 WHERE id = roll;
    ELSE
        SELECT * FROM table2 WHERE id = 2;
    END IF;
END //

DELIMITER ;

Wrong syntax:

DELIMITER //

CREATE PROCEDURE NAME(IN Number INT)
BEGIN
    IF roll= 1 THEN  SELECT * FROM table1 WHERE id = roll;
    ELSE   SELECT * FROM table2 WHERE id = 2;
    END IF;
END //

DELIMITER ;


来源:https://stackoverflow.com/questions/4294312/why-wont-simple-if-else-statement-work-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!