简体   繁体   English

如果ELSE语句在MySql中工作,为什么不简单

[英]Why won't simple If ELSE Statement work in mySql

I'm trying to create a simple stored procedure with an if else statement in SQLYog against a mySql db. 我正在尝试使用针对MySQL数据库的SQLYog中的if else语句创建一个简单的存储过程。 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 我对mySql语法不太熟悉,所以我希望它很简单,但我看不出为什么这不起作用

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; <BR> 1064您的SQL语法错误; 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 检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第5行的'ELSE SELECT * FROM tblProduct其中intProductId = 2 END IF'附近使用

Statements in MySQL are delimited by semicolons. MySQL中的语句由分号分隔。 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. 查看文档以了解是否有其他信息。

Remember the IF ELSE statement is always used in stored procedure, triggers not in simple select query. 请记住,IF ELSE语句始终在存储过程中使用,不会在简单的select查询中触发。 And ELSE OR IF keyword always write in new line not in front of query.Like below 而且ELSE OR IF关键字总是写在新行中而不是在查询前面。

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 ;

You need a ; 你需要一个 ; after your select statements. 选择语句后。 You also need BEGIN and END around your procedure body. 您还需要在过程主体周围添加BEGIN和END。 See the manual for lots of examples about the exact syntax for procedures. 有关过程的确切语法的大量示例,请参见手册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM