简体   繁体   English

带IF语句的MySQL存储过程

[英]MySQL Store Procedure with IF Statement

I need to define a mysql stored procedure that if you pass it a parameter, uses it in a select query and if you don't then it doesn't. 我需要定义一个mysql存储过程,如果您将其传递给参数,则在选择查询中使用它,如果没有,则不这样做。

Here's what i have, and it's not working : 这是我所拥有的,并且不起作用:

IF (selected_category IS NULL) then

SELECT i.id, i.name, i.summary, i.description, i.location, c.name AS 'category_name' 
FROM items i, categories c WHERE i.category_id = c.id;

ELSE IF (selected_category IS NOT NULL) then

SELECT i.id, i.name, i.summary, i.description, i.location, c.name AS 'category_name'
FROM items i, categories c WHERE i.category_id = c.id AND c.name LIKE selected_category;

END IF

I've also tried, instead of ELSE IF , to write ELIF , END IF; 我还尝试了代替ELSE IF来编写ELIFEND IF; and then a new IF but nothing wants to work. 然后创建新的IF但没有任何效果。

When I click the Create Procedure it always displays an error unless I comment out everything below the first SELECT . 当我单击“创建过程”时,它总是显示错误,除非我注释掉第一个SELECT下面的所有内容。

Help would be much appreciated. 帮助将不胜感激。 Thank you. 谢谢。

You can use only one query: 您只能使用一个查询:

SELECT i.id, i.name, i.summary, i.description, i.location, c.name AS 'category_name'
FROM items i, categories c 
WHERE i.category_id = c.id 
AND IF(selected_category IS NOT NULL, c.name LIKE CONCAT('%', selected_category,'%'), TRUE);

On a side note, please use explicit joins instead of implicit. 另外,请使用显式联接而不是隐式联接。

ps: I realize I didn't really answer your question, I just provided an alternative. ps:我知道我并没有真正回答你的问题,我只是提供了一个替代方案。 I think you just missed the ELSEIF statement. 我认为您只是错过了ELSEIF声明。 You are using ELSE IF and you tried ELIF , but it's apparently not the correct syntax . 您正在使用ELSE IF并尝试了ELIF ,但这显然不是正确的语法

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

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