6

我试图在 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);

有任何想法吗?

4

3 回答 3

8

我希望你的朋友是 FIND_IN_SET。我在这个问题中第一次遇到这种方法:也包括在这个问题中MYSQL - Stored Procedure Utilizing 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);

(ps修正了一个错字,在你的论点中你输入了categoy)

于 2013-04-19T11:43:06.690 回答
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$$
于 2013-04-19T11:43:03.523 回答
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');
于 2013-10-02T05:29:24.820 回答