FAHNZ

MODE

Transact SQL LastIndexOf Function

I can’t help but think there may be a more efficient way to do this, but I’m posting here anyway. I welcome updates to make this better…

CREATE FUNCTION LastIndexOf
(
@substring nvarchar(max),
@stringToSearch nvarchar(max)
)
RETURNS int
AS
BEGIN

RETURN
LEN(@stringToSearch)
- LEN(@substring)
+ 2
- CHARINDEX(REVERSE(@substring), REVERSE(@stringToSearch))

END
GO

I still can’t believe I didn’t find much on this (beyond a single character search) on Google. Go figure.


2 Responses to “Transact SQL LastIndexOf Function”

  1. tim says:

    You should checkout github gists, for stuff like this.

  2. admin says:

    Good point. Of course I’ll probably forget by the time I need something like this again. :P