当将逗号分隔的字符串作为 varchar 发送到 MySQL 存储过程时,我无法将该字符串用作 IN 子句的一部分并返回正确的结果。该字符串被截断为小数,并且仅使用第一个值。
我以为我可以通过准备然后执行语句来解决这个问题,但这仍然只返回第一个值的匹配项。
代码示例可能会让事情更清楚一些。我想将以下内容转换为存储过程(使用动态 in 子句):
select id, name from cities where id in (1,2,3);
这是我使用准备好的语句的存储过程:
DROP PROCEDURE IF EXISTS `cities_select_by_ids` $$
CREATE PROCEDURE `cities_select_by_ids`(
in _cityIds varchar(1000)
)
BEGIN
SET @cityIds = _cityIds;
PREPARE stmt FROM '
select
id,
name
from cities
where id in (?);
';
EXECUTE stmt USING @cityIds;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
调用存储过程我只得到城市“1”的匹配项:
call cities_select_by_ids_prepare('1, 2, 3');
这是表和数据的创建和插入脚本:
CREATE TABLE cities (
id int(10) unsigned NOT NULL auto_increment,
name varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
insert into cities (name) values ('London'), ('Manchester'), ('Bristol'), ('Birmingham'), ('Brighton');
最佳答案
试试这个。
DROP PROCEDURE IF EXISTS `cities_select_by_ids_2`;
CREATE PROCEDURE `cities_select_by_ids_2`(
in cityIDs varchar(1000)
)
BEGIN
#- ix - index into the list of city IDs
# cid - city ID
SET @ix := 1;
SET @cid := substring_index(cityIDs, ',', @ix);
LOOP_1:
WHILE (@cid is not null) DO
SELECT id, name
FROM cities
WHERE id in (@cid) ;
#-- substring_index returns complete cityIDs string when index is > number of elements
IF (length(substring_index(cityIDs, ',', @ix)) >= length(cityIDs)) THEN
LEAVE LOOP_1;
END IF;
SET @ix := @ix + 1;
SET @cid = substring_index(substring_index(cityIDs, ',', @ix), ',', -1);
END WHILE;
END
#----
call cities_select_by_ids_2('1, 2');
关于sql - 在 'in' 子句的存储过程中使用 MySQL 用户定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1601889/