43

In C#, we have String.LastIndexOf method to get a last index of a particular character location for given string. Is there any similar function to do same in SQL Server. I tried using CHARINDEX but couldn't able to achieve it.

Josh Burgess
  • 8,696
  • 30
  • 45
Mahender
  • 5,114
  • 7
  • 35
  • 53

3 Answers3

75

A little tricky, but you could do something like:

REVERSE(SUBSTRING(REVERSE([field]),0,CHARINDEX('[char]',REVERSE([field]))))
antinescience
  • 2,299
  • 21
  • 30
  • I had this stashed from http://stackoverflow.com/questions/1024978/find-index-of-last-occurrence-of-a-sub-string-using-t-sql, because it seems to come up pretty often. – antinescience Mar 29 '13 at 19:05
  • 2
    The answer here is more concise and efficient: http://stackoverflow.com/a/13610627/197591 – Neo Jan 29 '16 at 07:23
27
DECLARE @x VARCHAR(32) = 'xyzxyzyyythgetdghydgsh';
SELECT LEN(@x) - CHARINDEX('y', REVERSE(@x)) + 1;
Aaron Bertrand
  • 242,666
  • 35
  • 420
  • 451
0

Try this one out, analyze result step by step.


declare @string varchar(max)
declare @subString varchar(max)
set @string = 'this is a duplicated question,      but may get some new answers, since tech chagne from time to time as we know';
set @subString = 'this is a duplicated question,      but may get some new answers, since tech chagne from time to time'
--Find the string.lastIndexof(time)
select LEN(@String)
select LEN(@SubString)
select CHARINDEX('time', REVERSE(@string))
select reverse(@string)
select reverse('time')
SELECT LEN(@string) - CHARINDEX(reverse('time'), REVERSE(@string)) - Len('time') + 1
ljh
  • 2,438
  • 1
  • 12
  • 20