Search code examples
t-sqlsubstringcharindex

Need help in TSQL with Charindex


Need final output as S-05000_Chilling. Right now getting S-05000_Chilling_cle. Apparently, remove everything after last underscore symbol.

DECLARE @name varchar(100)
SET @name = 'abc.S-05000_Chilling_cleanup'
select substring(@name,CHARINDEX('.', @name)+1,(len(@name)-CHARINDEX('_', 
reverse(@name))))

Thanks in advance.


Solution

  • SELECT SUBSTRING(@name,CHARINDEX('.', @name)+1, 
        ( (LEN(@name)-CHARINDEX('.', @name))-CHARINDEX('_', REVERSE(@name) ) ) )