Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list of IDs to MySQL stored procedure?

I'm writing a stored procedure which should pass its arguments to IN (..) part of query in the procedure body, like this:

DELIMITER //  CREATE PROCEDURE `get_users_per_app` (id_list TEXT) BEGIN     SELECT app_id, GROUP_CONCAT(user_id) FROM app_users WHERE app_id IN (id_list) GROUP BY app_id; END//  DELIMITER ; 

This, obviously, doesn't work because when I pass a textual value, id_list is interpolated as an integer and only first ID is considered and used inside of IN() condition.

I realize that this particular type of procedure could be instead replaced by the contained query, but I think that my question still stands - what if I needed to pass this kind of data?

I also realize that this approach of query might not be considered the best practice, but in my use case it's actually better than returning a flat list of ID-ID pairs..

like image 284
mr.b Avatar asked Aug 21 '12 23:08

mr.b


People also ask

How do you pass a list of values into a stored procedure in SQL?

There are several ways to do this. While using older versions of SQL Server, I've used to the XML method to pass array or list to stored procedure. In the latest versions of SQL Server, we can use the User Defined Data Type (UDT) with a base type of table to send array or list through a parameter.

How do I pass a list of values in MySQL?

When you need to pass a list of parameters into a MySQL, there are at least two method to do this: Issue a dynamical query which would fill an IN list with constant values. Fill a temporary table with these values then use it in a JOIN.

How do you pass a list of values to a parameter of a stored procedure?

CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.

How do I pass a string array to a stored procedure in MySQL?

To create a stored routine that accepts an array as a parameter. Passing array as a parameter. mysql> delimiter ; mysql> call SearchingStoredProcedure('David,Bob,John');


1 Answers

You should be able to use MySQL's FIND_IN_SET() to use the list of ids:

CREATE PROCEDURE `get_users_per_app` (id_list TEXT) BEGIN     SELECT         app_id, GROUP_CONCAT(user_id)     FROM         app_users     WHERE         FIND_IN_SET(app_id, id_list) > 0     GROUP BY app_id;     ... 
like image 192
newfurniturey Avatar answered Sep 24 '22 18:09

newfurniturey