MYSQL split delimited strings functions

It's pretty easy to create your own string functions for many examples listed here

## Split delimited strings

CREATE FUNCTION strSplit(
x varchar(255),
delim varchar(12),
pos int
)
returns varchar(255)
return replace(substring(
substring_index(x, delim, pos),
length(substring_index(x, delim, pos - 1)) + 1),
delim, '');


select strSplit("aaa,b,cc,d", ',', 2) as second;
+--------+
| second |
+--------+
| b |
+--------+

select strSplit("a|bb|ccc|dd", '|', 3) as third;
+-------+
| third |
+-------+
| ccc |
+-------+

select strSplit("aaa,b,cc,d", ',', 7) as 7th;
+------+
| 7th |
+------+
| NULL |
+------+
Credits go to Chris Stubben

6 comments:

  1. Great function and very helpful.
    Hopefully it will be added in any case as native funtion.

    ReplyDelete
  2. I can't get it to work in mysql, can someone help?

    ReplyDelete
  3. Please describe the problem's symptoms.

    ReplyDelete
  4. I have a need for something similar. I have a table with 2 fields. id and value. ie id = 1 and value = 1,2,3,4. I need it in a new table with fields id = 1 and value1 = 1 and value2 = 2 and value3 = 3 and value4 = 4.

    Will a modification of your code work.

    ReplyDelete
  5. Well, we implement this and try out.. We had this coding section is out graduation studies.. you have reminding me on this topic.. thanks for the great coding..

    ReplyDelete
  6. Glad to visit this professional blog... I would love to learn more and more about technical and programming related things.. Great work!

    ReplyDelete