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..
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.
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.
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('.
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');
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; ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With