Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

How to do a LastIndexOf in sql

5.00/5 (2 votes)
31 Jan 2012CPOL 40.8K  
sometimes we need last occurance of the character in the string
The function below returns the position of the last occurrence of @char in @s. If @char does not exist in @s or @s is empty, 0 is returned. (First place in string is 1)

SQL
Create function GetLastCharIndex(@s varchar(max), @char varchar(200)) returns int
as
begin
 
 DECLARE  @lastIndex int
 DECLARE  @nOccurance int
 DECLARE @searchExpression varchar(max)
 SET @nOccurance = len(@s)
 SET @lastIndex = 0
 SET @searchExpression = @s
 
 while @nOccurance > 0
 BEGIN 
	SELECT @nOccurance = charIndex(@char, @searchExpression)
	IF (@nOccurance > 0)
	BEGIN
		SET @lastIndex = @lastIndex + @nOccurance
		SET @searchExpression = substring(@searchExpression, @nOccurance + 1, len(@searchExpression))
	END
 END

	
 return @lastIndex

end

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)