Click here to Skip to main content
15,904,156 members
Articles / Programming Languages / SQL
Tip/Trick

How to do a "LastIndexOf" in sql

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
31 Jan 2012CPOL 40.3K   1   2
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)


Written By
Software Developer (Senior) The Code Project
United States United States
Elina joined the Code Project team as a software developer in order to make the site run even smoother than it is now. She will also take care of making wishes and promises on the site improvements come to the light sooner than later. When not at work, she enjoys being with her family and wishes there will be at least 30 hours in a day Smile | :)

Comments and Discussions

 
QuestionAnother Option Pin
Member 293882513-Feb-14 1:13
Member 293882513-Feb-14 1:13 
QuestionA Little Shorter Suggestion Pin
dsacker10-Oct-12 10:33
dsacker10-Oct-12 10:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.