Friday, June 27, 2008

Get Filename from Filepath in T-SQL

Anatoly Lubarsky - T-SQL: Get Filename from Filepath

“…

Since there is no split function analog in T-SQL - I will use SUBSTRING, REVERSE and CHARINDEX to manipulate strings:

SELECT REVERSE(SUBSTRING(REVERSE(@fpath), 0, CHARINDEX('\', REVERSE(@fpath), 1)))
…”

I’ve reinvented this wheel a number of times and don’t think I’ve built one quite like the above…

Reversing it (no pun intended) will get you the filepath without the filename

SELECT
REVERSE
(
SUBSTRING
(
REVERSE((@fpath),
CHARINDEX('\', REVERSE((@fpath), 1) + 1,
LEN((@fpath) - CHARINDEX('\', REVERSE((@fpath), 1)
)
)

3 comments:

  1. I was getting errors from REVERSE about having one parameter and I found it necessary to edit that portion:

    REVERSE(SUBSTRING(REVERSE(@fpath),CHARINDEX('\', REVERSE(@fpath), 1) + 1,LEN(@fpath) - CHARINDEX('\', REVERSE(@fpath),1)))

    This post is the single best method I found to accomplish splitting the path apart.

    ReplyDelete
  2. Nice... thanks for the update/correction.

    ReplyDelete
  3. Try RIGHT( SourcePath, CHARINDEX( '\', REVERSE( SourcePath)) - 1)

    ReplyDelete

NOTE: Anonymous Commenting has been turned off for a while... The comment spammers are just killing me...

ALL comments are moderated. I will review every comment before it will appear on the blog.

Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...

I reserve, and will use, the right to not approve ANY comment for ANY reason. I will not usually, but if it's off topic, spam (or even close to spam-like), inflammatory, mean, etc, etc, well... then...

Please see my comment policy for more information if you are interested.

Thanks,
Greg

PS. I am proactively moderating comments. Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...