1

I would like to know how to accomplish getting just the file name from the below

C:\Users\avs\Desktop\Testing\Text Files\TargetFolder\PN005337.RCS

the PN005337.RCS file name can vary in name and length. However the only definitive way of capturing it would be looking at the last '\' and then bringing back any thing after the very last '\'.

Anyway to do that in sql. This is a column in sql server, but the report owner just wants to see the name.

I am doing this in SSIS so either solution would be great in an expression or in SQL.

Thank you

abs786123
  • 581
  • 2
  • 11
  • 24
  • Possible duplicate of [Parse file name and path from full path](http://stackoverflow.com/questions/19505875/parse-file-name-and-path-from-full-path) – JohnHC Oct 12 '16 at 08:48

2 Answers2

1

You could determine the index of the last slash by first REVERSE the path and then find the slash by means of CHARINDEX.
Finally you extract the filename applying to the original path the function RIGHT using the found index.

The expression would be RIGHT(path, CHARINDEX('/', REVERSE(path)) - 1)

Robert Kock
  • 5,795
  • 1
  • 12
  • 20
0

A case for CROSS APPLY to make intermediate computations

declare @t table (full_path varchar(max));
insert @t values 
 ('C:\Users\avs\Desktop\Testing\Text Files\TargetFolder\PN005337.RCS'), 
 ('C:PN005337.RCS'), 
 ('PN005337.RCS');


SELECT full_path, 
    CASE WHEN pback>=0 THEN RIGHT(full_path, pback) 
         WHEN pcol>=0 THEN RIGHT(full_path, pcol) 
         ELSE full_path
         END as fname
FROM  @t
CROSS APPLY (
    SELECT pback= CHARINDEX('\', REVERSE(full_path)) -1, pCol = CHARINDEX(':', REVERSE(full_path)) -1
    ) pp
Serg
  • 22,285
  • 5
  • 21
  • 48