So I am trying to find a substring from a table that holds a bunch of folder paths. I am trying to get the substring that exists between “C:\Root\ IWantThisString \otherstuff”. The problem with doing something like SUBSTRING(FilePath,9,CHARINDEX('\',FilePath,9) - 9) is that when I have a path that looks like “C:\Root\ IWantThisString” it returns an error because the charindex never finds a last ‘\’ after “Root\” (because there is no third ‘\’ in this case).
So is there an easy way to do something like this?
SELECT SUBSTRING(FilePath,9,(
IF (CHARINDEX('\',FilePath,9) = 0)
BEGIN
LEN(FilePath)
ELSE
CHARINDEX('\',FilePath,9) - 9
END))
FROM Table
Or something like that?
Ha! I found a ridiculously simple answer, I can just add a backslash to the end of each string. It works perfectly!
SELECT SUBSTRING(FilePath,9,(CHARINDEX('\',FilePath + '\',9) - 9))