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

白昼怎懂夜的黑 提交于 2019-12-20 02:38:05

问题


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

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

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

This returns: EXCHANGEUNIT P1i

I need to get only P1i with the query.

Thanks in advance.


回答1:


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

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 ) )


来源:https://stackoverflow.com/questions/8444175/get-the-last-word-of-a-part-of-a-varchar-left-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!