how to use WHERE IN mysql stored procedure

元气小坏坏 提交于 2021-02-16 13:02:44

问题


How do I pass an array and use WHERE IN inside stored procedure?

Do i need to concatenate input string or something ?

Lets say

DELIMITER $$
DROP PROCEDURE IF EXISTS `abc`.`table1`$$
CREATE PROCEDURE  `abc`.`test`
(IN somestring VARCHAR(255))
BEGIN
    SELECT * FROM abc.table1 
    WHERE flight_type IN somestring
END $$
DELIMITER ;

回答1:


You can use the string concatenation and the PREPARE statement to run dynamically built queries.

somestring must be constructed in a valid SQL format like '1','2','3'

DELIMITER $$
DROP PROCEDURE IF EXISTS `abc`.`table1`$$
CREATE PROCEDURE  `abc`.`test`
(IN somestring VARCHAR(255))
BEGIN
    @s=CONCAT("
    SELECT * FROM abc.table1 
    WHERE flight_type IN (",somestring,");")
    PREPARE stmt FROM @s;
    EXECUTE @s;
END $$
DELIMITER ;



回答2:


You can use FIND_IN_SET() if somestring is formatted a,b,c,d:

SELECT *
FROM abc.table1
WHERE FIND_IN_SET(flight_type, somestring)



回答3:


This should work as long as somestring is of the form

"(item1, item2, item3, ... )"

if not, you could format it accordingly inside of your SP but I'm not sure what the best practice is.




回答4:


The accepted answer needed modification to work with my version of MariaDB.

The CONCAT statement was missing a semicolon, The EXECUTE statement was called on @s (a variable) rather than stmt (a statement), and the drop/create portion was confusing. Here's my rewrite:

DELIMITER $$
DROP PROCEDURE IF EXISTS `dbname`.`procedurename`$$
CREATE PROCEDURE  `dbname`.`procedurename`
(IN somestring VARCHAR(255))
BEGIN
    SET @s=CONCAT("
    SELECT * FROM dbname.table1 
    WHERE flight_type IN (",somestring,");");
    PREPARE stmt FROM @s;
    EXECUTE stmt;
END $$
DELIMITER ;


来源:https://stackoverflow.com/questions/5373495/how-to-use-where-in-mysql-stored-procedure

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