This does not directly answer the question, but as I have found this while looking for a solution for extracting multiple values from a single string, with a specific delimiter, I post it anyway in case it could help someone.
SQL Server ships with the function PARSENAME that can extract up to 4 elements in a dot separated string, from the right :
SELECT PARSENAME('1234.5437.43278.532', 2) as third_element
--43278
You could use this function to retrieve the 2nd to the 5th element of the file name, by selecting from the second element to the end of the filename, without the extension.
Note that the code to remove the file extension (the 4th position from the right) is hardcoded here, so it's better to change it if you have some mix with .jpg and .jpeg file extensions for instance.
DECLARE @t TABLE (
c_filename VARCHAR(1000)
) INSERT @t
values
('abc_1_2_3_4.gif'),
('abcdefgh_1231_78432_398389_12144.png')
SELECT
LEFT(
c_filename,
CHARINDEX('_', c_filename) -1
) as first_element,
PARSENAME(
REPLACE(
/* PARSENAME only works with 4 elements */
/* we remove :
- the 1st element
- and the file extension */
SUBSTRING(
c_filename,
CHARINDEX('_', c_filename) + 1,
LEN(c_filename) - CHARINDEX('_', c_filename) -4
),
'_',
'.'
),
4 -- change this to get the nth element
) as second_element,
PARSENAME(
REPLACE(
SUBSTRING(
c_filename,
CHARINDEX('_', c_filename) + 1,
LEN(c_filename) - CHARINDEX('_', c_filename) -4
),
'_',
'.'
),
3
) as third_element,
PARSENAME(
REPLACE(
SUBSTRING(
c_filename,
CHARINDEX('_', c_filename) + 1,
LEN(c_filename) - CHARINDEX('_', c_filename) -4
),
'_',
'.'
),
2
) as fourth_element,
PARSENAME(
REPLACE(
SUBSTRING(
c_filename,
CHARINDEX('_', c_filename) + 1,
LEN(c_filename) - CHARINDEX('_', c_filename) -4
),
'_',
'.'
),
1
) as fifth_element
FROM
@t
+---------------+----------------+---------------+----------------+---------------+
| first_element | second_element | third_element | fourth_element | fifth_element |
+---------------+----------------+---------------+----------------+---------------+
| abc | 1 | 2 | 3 | 4 |
| abcdefghijkl | 12qwerty31 | 78891432 | 398977389 | 1212345344 |
+---------------+----------------+---------------+----------------+---------------+