Created
January 12, 2023 15:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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