user5245950
user5245950

Reputation:

T-SQL 2008: Parse String

I have the following location as a string:

\\Windows\UnitB\CU1234_001\

I want to return the CU1234_001 part only. The query which I need to use needs to be dynamic since this string will change and it could be longer or shorter (it will all the time end in "\".

I've tried to used something like this but this just eliminate the last "\" and returns the rest of the string:

select 
    substring('\\Windows\UnitB\CU1234_001\',
              1, (len('\\Windows\UnitB\CU1234_001\') - (Charindex('\',  
  reverse(rtrim('\\Windows\UnitB\CU1234_001\'))))))

Upvotes: 1

Views: 36

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521178

You can use a combination of string functions to extract what you want:

SELECT REVERSE(SUBSTRING(REVERSE(col),
                         2,
                         CHARINDEX('/', REVERSE(col), 2) - 2))
FROM yourTable

Upvotes: 1

Related Questions