I need to pass an array of strings as parameter to a MySQL stored routine. The array could be long and its number of elements is not fixed. I then want to put the string values into an in-memory table with one column, so I can work with the data. I don't know if this can be done in MySQL. Maybe dirty workarounds are needed.
For example, I have the string values:
Banana, Apple, Orange
Now I want to get data on these fruits from my MySQL Fruits
table. Pseudo code:
create function GetFruits(Array fruitArray) declare @temp table as fruitName varchar(100) end @temp = convert fruitArray to table select * from Fruits where Name in (select fruitName from @temp) end
Microsoft SQL Server allows you to use the TEXT
datatype and submit the array as an XML string, swiftly creating the in-memory table. However, I don't think that technique is possible in MySQL.
Any help on how to do this would be appreciated!
MySQL Stored Procedures do not provide an array data type. You could implode the php array to a separated string and pass this string as VARCHAR(255) to the stored procedure.
Try using FIND_IN_SET() function of MySql e.g. SET @c = 'xxx,yyy,zzz'; SELECT * from countries WHERE FIND_IN_SET(countryname,@c); Note: You don't have to SET variable in StoredProcedure if you are passing parameter with CSV values. Voting is disabled while the site is in read-only mode.
Although an array is one of the most common data types in the world of programming, MySQL actually doesn't support saving an array type directly. You can't create a table column of array type in MySQL. The easiest way store array type data in MySQL is to use the JSON data type.
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('.
You can pass a string with your list and use a prepared statements to run a query, e.g. -
DELIMITER $$ CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255)) BEGIN SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; END $$ DELIMITER ;
How to use:
SET @fruitArray = '\'apple\',\'banana\''; CALL GetFruits(@fruitArray);
Simply use FIND_IN_SET like that:
mysql> SELECT FIND_IN_SET('b','a,b,c,d'); -> 2
so you can do:
select * from Fruits where FIND_IN_SET(fruit, fruitArray) > 0
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