Skip to content

Instantly share code, notes, and snippets.

@jgdoncel
Created January 12, 2023 15:18
Show Gist options
  • Save jgdoncel/81441c5561706d61050f6cb2b1b38db6 to your computer and use it in GitHub Desktop.
Save jgdoncel/81441c5561706d61050f6cb2b1b38db6 to your computer and use it in GitHub Desktop.
MySQL: Function to split string based on a separator and an extraction index
/*
Usage:
SELECT fn_split_string('20156 2018-01-25',' ',1) AS one, fn_split_string('20156 2018-01-25',' ',2) AS two;
+-------+------------+
| one | two |
+-------+------------+
| 20156 | 2018-01-25 |
+-------+------------+
*/
CREATE FUNCTION `fn_split_string`(
str VARCHAR(255) ,
delim VARCHAR(12) ,
pos INT
) RETURNS varchar(255) CHARSET utf8
RETURN REPLACE(
SUBSTRING(
SUBSTRING_INDEX(str, delim, pos),
CHAR_LENGTH(
SUBSTRING_INDEX(str , delim , pos - 1)
) + 1
),
delim ,
''
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment