MySQL stored procedure passing array of number in parameters

时间:2015-07-08 15:47:46

标签: mysql stored-procedures parameters where-clause

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

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

You just need to use a split function, do it by comma.

The way you pass it now is a single string.

答案 2 :(得分:0)

今天在 this page

上发现的
SET @c = 'xxx,yyy,zzz';
SELECT * from table 
WHERE FIND_IN_SET(columnname,@c);

对我有用。