Skip to content

Instantly share code, notes, and snippets.

@leewin12
Forked from mikedamage/split_str.sql
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leewin12/9038563 to your computer and use it in GitHub Desktop.
Save leewin12/9038563 to your computer and use it in GitHub Desktop.
MySQL Split User-defined function
-- SPLIT_STR MySQL Function
-- from http://blog.fedecarg.com/2009/02/22/mysql-split-string-function/
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
-- use CHAR_LENGTH instead of LENGTH to support utf8
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
CHAR_LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
/*
Example:
SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;
+-------+
| third |
+-------+
| ccc |
+-------+
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment