MySql存储过程和逗号分隔Varchar与In语句

时间:2013-12-08 10:34:02

标签: mysql stored-procedures

我正在尝试创建一个存储过程,该过程将逗号分隔列表作为值并将其推送到带有IN子句的select语句中。我知道find_in_set有效,但确实有性能开销。我还试用了一份准备声明,但问题仍然存在。

我的例子:

我的参数是sp1并包含值:'valuex,valuey,valuez'。

BEGIN

    set @sql = concat('select *  from tablename WHERE assignedTo in (', sp1, ')');

    PREPARE q FROM @sql;

    execute q;

END

正如预期的那样,这会引发错误,因为SQL会将值视为列名。我的问题是如何实现:'valuex','valuey','valuez'FROM'valuex,valuey,valuez'?

2 个答案:

答案 0 :(得分:3)

您可以使用replace功能:

BEGIN

    set @sql = concat("select *  from tablename WHERE assignedTo in ('", replace(sp1,",","','"), "')");

    PREPARE q FROM @sql;

    execute q;

END

答案 1 :(得分:2)

选项是:

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_test`$$

CREATE PROCEDURE `sp_test`(`sp1` VARCHAR(50))
BEGIN
    SET `sp1` := REPLACE(REPLACE(`sp1`, ', ', ','), ',', '\',\'');
    SET @`query` := CONCAT('SELECT `column0`, `column1` FROM `tablename` WHERE `assignedTo` IN (\'', `sp1`, '\');');
    PREPARE `stmt` FROM @`query`;
    EXECUTE `stmt`;
    DEALLOCATE PREPARE `stmt`;
END$$

DELIMITER ;

CALL `sp_test`('valuex, valuey, valuez');
-- SELECT `column0`, `column1` FROM `tablename` WHERE `assignedTo` IN ('valuex','valuey','valuez');