When sending a string of comma-separated identifiers like varchar to a MySQL stored procedure, I cannot use this string as part of an IN clause to return the correct results. The string is truncated as decimal and only the first value is used.
I thought I could get around this by preparing and then following the instructions, but that still returned a match for the first value.
Code examples can make things more clear. I want to convert the following to a stored procedure (with dynamic in a section):
select id, name from cities where id in (1,2,3);
This is my stored procedure using a prepared statement:
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 ;
Calling a stored procedure I get only a match for the city '1':
call cities_select_by_ids_prepare('1, 2, 3');
Here, create and paste the script for the table and data:
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');