Best way to get last index character in SQL 2008

In C #, we have a String.LastIndexOf method to get the last index of a specific character location for a given string. Is there a similar feature to do the same in SQL Server. I tried to use CHARINDEX but could not reach it.

+43
string sql sql-server-2008
Mar 29 '13 at 18:58
source share
3 answers

A bit complicated, but you can do something like:

 REVERSE(SUBSTRING(REVERSE([field]),0,CHARINDEX('[char]',REVERSE([field])))) 
+73
Mar 29 '13 at 19:00
source share
 DECLARE @x VARCHAR(32) = 'xyzxyzyyythgetdghydgsh'; SELECT LEN(@x) - CHARINDEX('y', REVERSE(@x)) + 1; 
+28
Mar 29 '13 at 19:01
source share

Try it, analyze the 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 
0
Mar 29 '13 at 19:16
source share



All Articles