SQL 获取 varchar 一部分的最后一个单词(左/右)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8444175/
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 13:35:47  来源:igfitidea点击:

Get the last word of a part of a varchar (LEFT/RIGHT)

sqlsql-server-2005tsql

提问by Tim Schmelter

What is the correct way to get the last word of a part of a varchar?

获取 varchar 一部分的最后一个字的正确方法是什么?

DECLARE @desc varchar(100)
SET @desc='EXCHANGEUNIT P1i / SILVERBLACK/ CYRILLIC'

SELECT RTRIM(LEFT(@desc, CHARINDEX('/', @desc) - 1))

This returns: EXCHANGEUNIT P1i

这将返回: EXCHANGEUNIT P1i

I need to get only P1iwith the query.

我只需要得到P1i查询。

Thanks in advance.

提前致谢。

回答by

Use a combination of REVERSE, LEFT and CHARINDEX - like so:

使用 REVERSE、LEFT 和 CHARINDEX 的组合 - 像这样:

DECLARE @desc varchar(100)
SET @desc='EXCHANGEUNIT P1i / SILVERBLACK/ CYRILLIC'
SET @subdesc=RTRIM(LEFT(@desc, CHARINDEX('/', @desc) - 1))


SELECT REVERSE( LEFT( REVERSE(@subdesc), CHARINDEX(' ', REVERSE(@subdesc))-1 ) )