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.

4

3 回答 3

75

A little tricky, but you could do something like:

REVERSE(SUBSTRING(REVERSE([field]),0,CHARINDEX('[char]',REVERSE([field]))))
于 2013-03-29T19:00:44.223 回答
27
DECLARE @x VARCHAR(32) = 'xyzxyzyyythgetdghydgsh';
SELECT LEN(@x) - CHARINDEX('y', REVERSE(@x)) + 1;
于 2013-03-29T19:01:00.653 回答
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
于 2013-03-29T19:16:06.733 回答