在 SQL 2008 中获取最后一个 indexof 字符的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15709712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:33:02  来源:igfitidea点击:

What is best way to get last indexof character in SQL 2008

sqlstringsql-server-2008

提问by Mahender

In C#, we have String.LastIndexOfmethod 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 CHARINDEXbut couldn't able to achieve it.

在 C# 中,我们有String.LastIndexOf方法获取给定字符串的特定字符位置的最后一个索引。在 SQL Server 中是否有类似的功能可以做同样的事情。我尝试使用CHARINDEX但无法实现。

回答by antinescience

A little tricky, but you could do something like:

有点棘手,但您可以执行以下操作:

REVERSE(SUBSTRING(REVERSE([field]),0,CHARINDEX('[char]',REVERSE([field]))))

回答by Aaron Bertrand

DECLARE @x VARCHAR(32) = 'xyzxyzyyythgetdghydgsh';
SELECT LEN(@x) - CHARINDEX('y', REVERSE(@x)) + 1;

回答by ljh

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