Get the last word of a part of a varchar (LEFT/RIG

2019-02-27 10:21发布

问题:

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