sql - 在 'in' 子句的存储过程中使用 MySQL 用户定义变量

标签 sql mysql stored-procedures

当将逗号分隔的字符串作为 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/

相关文章:

mysql - SQL 查询 - 选择不同的类别和计数

java - 存储过程向结果集返回 null

sql-server-2005 - 存储过程中的冒泡错误

javascript - 查看 Node.js 代码

.net - 使用 DbConnection 执行存储过程

sql - 向 UTL_MAIL.SEND 提供凭据以绕过 ORA-29278

sql - 选择重叠的时间范围

sql - MySQL 高级选择帮助

mysql - 从 SQL 中的同一行返回最小值的列名

php - 在连接中添加数据库名称时出现连接错误