In sql server we have a charindex function that returns us the index of a specific character inside a string. It returns the position of the first occurrence. But often we need to find out the position of nth occurrence of a character inside a string. There is no built in function for this. But we can easily write one.
CREATE FUNCTION [dbo].[fn_NTH_OCCURRENCE] (@STR VARCHAR(MAX), @CHAR VARCHAR(1), @OCCURRENCE INT)
RETURNS INT
BEGIN
SELECT @STR = STUFF(@STR, CHARINDEX(@CHAR, @STR), 1, ‘*’)
FROM DBO.INTEGERSEQUENCE(1, @OCCURANCE-1)
RETURN ISNULL(CHARINDEX(@CHAR, @STR), 0)
END
GO
SELECT [dbo].[fn_NTH_OCCURRENCE](‘dbo.fn_PERCENTAGE([2109],[2103])’, ‘[‘, 2)
The function will return 26. So this is skipping the first position and returning the position of the second occurrence.
This function takes 3 parameters.
- @STR : this is the string where we want to find the nth occurrence of a character.
- @CHAR : this is the character that we want to find.
- @OCCURRENCE : this is an integer. We will get the @CHAR position for this occurrence.
If the @OCCURRENCE is larger than the total number of occurrence inside the string, then the function returns 0.
This function does not use any while loop. Instead of that it uses a table valued function to generate that generates integer sequence. To get this DBO.INTEGERSEQUENCE function, please see the following post.
Integer Sequence Generator Using CTE (Common Table Expression)
Integer sequence generator, Date sequence generator