我正在尝试在MySQL存储过程中将数组作为字符串传递,但它不能正常工作。
这是我的SQL代码:
CREATE DEFINER=`root`@`localhost` PROCEDURE `search_equipment`(IN equip VARCHAR(100), IN category VARCHAR(255))
BEGIN
SELECT *
FROM Equipment
WHERE e_description
LIKE CONCAT("%",equip,"%")
AND e_type IN (category)
END
以下是我称之为程序的方式:
String type = "'I.T. Equipment','Office Supply'";
CALL search_equipment('some equipment', type);
有什么想法吗?
答案 0 :(得分:6)
你的朋友在这里是我期待的FIND_IN_SET。我首先在这个问题中遇到过这种方法:这个问题也包括MYSQL - Stored Procedure Utilising Comma Separated String As Variable Input
FIND_IN_SET的MySQL文档在http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
所以你的程序将成为
CREATE DEFINER=`root`@`localhost`
PROCEDURE `search_equipment`(
IN equip VARCHAR(100),
IN category VARCHAR(255)
)
BEGIN
SELECT *
FROM Equipment
WHERE e_description LIKE CONCAT("%",equip,"%")
AND FIND_IN_SET(e_type,category)
END
这依赖于类别字符串是以逗号分隔的列表,因此您的调用代码变为
String type = "I.T. Equipment,Office Supply";
CALL search_equipment('some equipment', type);
(p.s。修正了一个拼写错误,在你的论据中你输入了类别)
答案 1 :(得分:2)
你必须创建一个动态的陈述:
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `search_equipment`(IN equip VARCHAR(100), IN category VARCHAR(255))
BEGIN
SET @s =
CONCAT('SELECT *
FROM Equipment
WHERE e_description
LIKE \'%',equip,'%\'
AND e_type IN (',category,')');
PREPARE stmt from @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt3;
END$$
答案 2 :(得分:0)
这有助于我做IN条件 希望这会对你有帮助..
CREATE PROCEDURE `test`(IN Array_String VARCHAR(100))
BEGIN
SELECT * FROM Table_Name
WHERE FIND_IN_SET(field_name_to_search, Array_String);
END//;
通话:
call test('3,2,1');