Search code examples
mysqlstored-proceduresparameterswhere-clause

MySQL stored procedure passing array of number in parameters


I'am not sure what I've been doing wrong ...

I have a simple query :

SELECT * FROM locations WHERE (ID IN (1, 2, 3, 4, 5));

now I just took that query and made it into a store procedure with an arguments of type LONGTEXT

sp_FetchMultipleLocations(IN argLocations LONGTEXT)
BEGIN
    SELECT * FROM locations WHERE (ID IN (argLocations));
END;

then I call that stored procedures with multiples values in that parameters :

CALL sp_FetchMultipleLocations('1, 2, 3, 4, 5');

but the IN statement in the where clause doesn't seem to be working, it shows me only the first(1) location ... why is that ?

thanks


Solution

  • The argument is a single monolithic string. Just because you're using that argument in an IN clause inside the sproc doesn't mean MySQL knows it should tear apart that csv string into individual values - it has no idea what CSV is, nor should it.

    You'll have to use dynamic sql, e.g. in pseudo-ish code:

    procedure foo(in args longtext)
    begin
        sql = concat('SELECT ... WHERE foo IN (', args, ')')
        execute @sql
    end