Created
January 3, 2014 15:15
-
-
Save gregtyler/8239482 to your computer and use it in GitHub Desktop.
MySQL function to find the nth occurrence of a substring in a string.
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
# Drop the function if it's already there | |
drop function if exists LOCATE_OFFSET; | |
# Define the function | |
# @param substr The substring to search for | |
# @param str The string to search through | |
# @param offset The nth-occurrence being looked for (1-indexed, using 0 will always return 0) | |
DELIMITER // | |
CREATE FUNCTION LOCATE_OFFSET(substr text, str text, offset int) | |
RETURNS int | |
DETERMINISTIC | |
BEGIN | |
DECLARE loc INT DEFAULT 1; | |
DECLARE i INT DEFAULT 0; | |
WHILE(i<offset) DO | |
SET loc=LOCATE(substr, str, loc+1); | |
SET i=i+1; | |
END WHILE; | |
RETURN(loc); | |
END// | |
DELIMITER ; | |
# Example | |
# Returns 7 | |
SELECT LOCATE_OFFSET( 'bar', 'foobarbar', 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for sharing this stored function.
Changing lines 15 - 18 to:
will make this function return NULL instead of strange values, when attempting to return an occurrence that does not exist.