DECLARE @urls TABLE (URL varchar(2000))
INSERT @urls VALUES ('\\myserver\mydir1\dir2\test.txt')
INSERT @urls VALUES ('\\myserver2\dir1\dir2\dir3\test.txt')
SELECT
REVERSE(SUBSTRING(REVERSE(URL), CHARINDEX('\', REVERSE(URL))+1, 8000))
FROM
@urls
Logic:
\\myserver\mydir1\dir2\test.txt
- REVERSE =
txt.tset\2rid\1ridym\revresym\
- look for first
\
- take everything after that SUBSTRING =
2rid\1ridym\revresym\
- REVERSE =
\\myserver\mydir1\dir2
You don't need to know the LEN of the string for the SUBSTRING so just use 8000
Edit, after comment about using 8000
- You can use 2147483647 in SUBSTRING because it supports max types
- Only has to be equal to or longer that the varchar variable or column length
- What about the overhead of calculating LEN?
- Practically all URLs have to fit into 2083 bytes
- Does it matter? "Premature optimisation" etc