My data will be like that
IPDocument/XR/test_20120409_clearGAC.txt
IPDocument/XR/test_20120409_clearGAC_05.txt
IPDocument/XR/test_20120409_clearGAC_01.txt
SELECT SUBSTRING('IPDocument/XR/test_20120409_clearGAC.txt', CHARINDEX('09_','IPDocument/XR/test_20120409_clearGAC.txt')+3, 100)
result : clearGAC.txt
I assume that you want the _05 and _01 - the question is not clear.
DECLARE @var VARCHAR(250)
DECLARE @table TABLE ( val VARCHAR(250) )
INSERT INTO @table
SELECT 'IPDocument/XR/test_20120409_clearGAC_01.txt'
UNION ALL
SELECT 'IPDocument/XR/test_20120409_clearGAC_05.txt'
UNION ALL
SELECT 'IPDocument/XR/test_20120409_clearGAC.txt'
SELECT SUBSTRING(val, CHARINDEX('clearGAC', val), 50),
SUBSTRING(SUBSTRING(val, CHARINDEX('_', val)+1, 50), CHARINDEX('_', SUBSTRING(val, CHARINDEX('_', val)+1, 50))+1, 50)
FROM @table
Returns this:
clearGAC_01.txt
clearGAC_05.txt
clearGAC.txt
The third parameter in the CHARDINDEX can be larger than the length.
EDIT: I added logic if you don't know if clearGAC
is the name
After reading your comment, you may just want this:
I am going to pass ClearGAC.txt and see if it's in the DB. this ClearGAC.txt may be named like above codes.
DECLARE @var VARCHAR(250)
DECLARE @table TABLE ( val VARCHAR(250) )
INSERT INTO @table
SELECT 'IPDocument/XR/test_20120409_clearGAC_01.txt'
UNION ALL
SELECT 'IPDocument/XR/test_20120409_clearGAC_05.txt'
UNION ALL
SELECT 'IPDocument/XR/test_20120409_clearGAC.txt'
SELECT *
FROM @table
WHERE val LIKE '%clearGAC%.txt'