Technical Article

Function To Retrieve Last Index

,

This Function Enables the user to retrieve the Last Index of the character/string in a predetermined string.
Eg
If you want search for the Last Occurance of 'SQL' in
'SQL SERVER2000 USES ANSI SQL' then
SELECT dbo.LastIndexOf('SQL SERVER2000 USES ANSI SQL','SQL')
will return
26.

Tested Only in SQL SERVER2000



CREATE  FUNCTION LastIndexOf 
(@strValue VARCHAR(4000),
@strChar VARCHAR(50)) 
RETURNS INT
AS
BEGIN
DECLARE @index INT

SET @index = 0

WHILE  CHARINDEX(@strChar, @strValue) > 0
BEGIN
SET @index = @index + CASE WHEN CHARINDEX(@strChar, @strValue) > 1 
   THEN 
(LEN(@strValue) - LEN(SUBSTRING(@strValue,CHARINDEX(@strChar, @strValue) + LEN(@strChar),LEN(@strValue)))) 
    ELSE 
1 
    END
SET @strValue = SUBSTRING(@strValue,CHARINDEX(@strChar, @strValue) + len(@strChar),LEN(@strValue))
END

RETURN @index 
END

Rate

5 (3)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (3)

You rated this post out of 5. Change rating