为什么不简单的 If ELSE 语句在 mySql 中工作 [英] Why won't simple If ELSE Statement work in mySql
问题描述
我正在尝试使用 SQLYog 中的 if else 语句针对 mySql 数据库创建一个简单的存储过程.我对 mySql 语法不太熟悉,所以我希望它很简单,但我不明白为什么这不起作用
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:
错误代码:1064您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在 'ELSE SELECT * FROM tblProduct where intProductId = 2 附近使用的正确语法END IF' 在第 5 行
推荐答案
MySQL 中的语句用分号分隔.要使用它们创建过程,您需要做一个像这样的小技巧:
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 ;
查看文档以了解 if/else了解更多信息.
Check out the documentation for if/else for more info.
这篇关于为什么不简单的 If ELSE 语句在 mySql 中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!