[英]How to Pass a List of String in MySQL Stored Procedure?
I'm trying to pass an array as a String in MySQL Stored Procedure but it doesn't work fine. 我试图在MySQL存储过程中将数组作为字符串传递,但它不能正常工作。
Here's my SQL Codes: 这是我的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
And here's how i call the procedure: 以下是我称之为程序的方式:
String type = "'I.T. Equipment','Office Supply'";
CALL search_equipment('some equipment', type);
Any ideas? 有任何想法吗?
Your friend here is FIND_IN_SET I expect. 你在这里的朋友是我期待的FIND_IN_SET。 I first came across that method in this question : also covered in this question MYSQL - Stored Procedure Utilising Comma Separated String As Variable Input
我在这个问题中第一次遇到了这个方法:在这个问题中也包含了MYSQL - 使用逗号分隔字符串作为变量输入的存储过程
MySQL documention for FIND_IN_SET is here http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set FIND_IN_SET的MySQL文档在这里http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
So your procedure will become 所以你的程序将成为
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
This relies on the category string being a comma-delimited list, and so your calling code becomes 这依赖于类别字符串是逗号分隔的列表,因此您的调用代码变为
String type = "I.T. Equipment,Office Supply";
CALL search_equipment('some equipment', type);
(ps fixed a typo, in your arguments you had typed categoy) (ps修正了一个拼写错误,在你的参数中你输入了类别)
you have to create a dynamic statment: 你必须创建一个动态的声明:
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$$
This helps for me to do IN condition Hope this will help you.. 这有助于我做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//;
Calling: 呼叫:
call test('3,2,1');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.