This answer uses MS SQL Server 2008 (I don't have access to MS SQL Server 2000), but the way I see it according to the OP are 3 situations to take into consideration. From what I've tried no answer here covers all 3 of them:
- Return the last index of a search character in a given string.
- Return the last index of a search sub-string (more than just a single
character) in a given string.
- If the search character or sub-string is not in the given string return
0
The function I came up with takes 2 parameters:
@String NVARCHAR(MAX) : The string to be searched
@FindString NVARCHAR(MAX) : Either a single character or a sub-string to get the last
index of in @String
It returns an INT that is either the positive index of @FindString in @String or 0 meaning that @FindString is not in @String
Here's an explanation of what the function does:
- Initializes
@ReturnVal to 0 indicating that @FindString is not in @String
- Checks the index of the
@FindString in @String by using CHARINDEX()
- If the index of
@FindString in @String is 0, @ReturnVal is left as 0
- If the index of
@FindString in @String is > 0, @FindString is in @String so
it calculates the last index of @FindString in @String by using REVERSE()
- Returns
@ReturnVal which is either a positive number that is the last index of
@FindString in @String or 0 indicating that @FindString is not in @String
Here's the create function script (copy and paste ready):
CREATE FUNCTION [dbo].[fn_LastIndexOf]
(@String NVARCHAR(MAX)
, @FindString NVARCHAR(MAX))
RETURNS INT
AS
BEGIN
DECLARE @ReturnVal INT = 0
IF CHARINDEX(@FindString,@String) > 0
SET @ReturnVal = (SELECT LEN(@String) -
(CHARINDEX(REVERSE(@FindString),REVERSE(@String)) +
LEN(@FindString)) + 2)
RETURN @ReturnVal
END
Here's a little bit that conveniently tests the function:
DECLARE @TestString NVARCHAR(MAX) = 'My_sub2_Super_sub_Long_sub1_String_sub_With_sub_Long_sub_Words_sub2_'
, @TestFindString NVARCHAR(MAX) = 'sub'
SELECT dbo.fn_LastIndexOf(@TestString,@TestFindString)
I have only run this on MS SQL Server 2008 because I don't have access to any other version but from what I've looked into this should be good for 2008+ at least.
Enjoy.