Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split comma separated text in MySQL stored procedure

Tags:

sql

mysql

How to split comma separated text (list of IDs) in MySQL stored procedure to use result in SQL "IN" statement.

SELECT * FROM table WHERE table.id IN (splitStringFunction(commaSeparatedData, ','));
like image 215
Peter Stegnar Avatar asked Feb 02 '10 08:02

Peter Stegnar


People also ask

How split comma separated values in SQL query MySQL?

You could use a prepared statement inside the stored procedure to achieve this. You can create the whole select query as a string inside a variable and then concatenate in the comma delimited string into its IN clause. Then you can make a prepared statement from the query string variable and execute it.

How split multiple comma separated values in SQL query?

Split comma-separated value string in a column. SELECT ProductId, Name, value FROM Product CROSS APPLY STRING_SPLIT(Tags, ','); Here is the result set. The order of the output may vary as the order is not guaranteed to match the order of the substrings in the input string.

How do I split a string in MySQL?

In MySQL, we use SUBSTRING_INDEX() to split the string. It usually consists of three arguments i.e., string, delimiter, and position. The string value will be split based on the position.


2 Answers

This is simple as hell for MySQL:

SELECT * FROM table WHERE FIND_IN_SET(table.id, commaSeparatedData);

Reference: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

like image 151
DarkSide Avatar answered Oct 05 '22 07:10

DarkSide


You could use a prepared statement inside the stored procedure to achieve this. You can create the whole select query as a string inside a variable and then concatenate in the comma delimited string into its IN clause. Then you can make a prepared statement from the query string variable and execute it.

DELIMITER ;;
create procedure testProc(in listString varchar(255))

BEGIN

set @query = concat('select * from testTable where id in (',listString,');');
prepare sql_query from @query;
execute sql_query;

END
;;

DELIMITER ;

call testProc("1,2,3");
like image 42
Lee Fentress Avatar answered Oct 05 '22 07:10

Lee Fentress