Sql server query to get Filename from Filepath

I need an sql query for Sql server 2014

 I have fileds DocNo ,Docpath and more fields on a Docs table

    DocPath field currently has relative path like  \mypath\fold1\subfold1\mydoc.docx  . I need to have the value only as just the file name

 sample existting values

  I should get the values modified as
Sam OZAsked:
Who is Participating?
Try this code to update:
create view DocView as 
select ID, right(TableDocs.DocPath, charindex('\', reverse(TableDocs.DocPath) + '\') -1) as DocPath
 from TableDocs
update TableDocs set  TableDocs.DocPath = DocView.DocPath from DocView
where TableDocs.ID = [DocView].[ID]

Open in new window

Try this code:
select right(TableDocs.DocPath, charindex('\', reverse(TableDocs.DocPath) + '\') - 1) from TableDocs

Open in new window

ste5anSenior DeveloperCommented:
Use the correct domains. Thus store the path separate from the filename and extension. Even the extension should be separated, when you need to query it somewhere. Cause your current column is not atomic, violating 1NF.

And consider a user using Linux. Then the path delimiter is /.
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Sam OZAuthor Commented:
Hi Misha. I am looking for update not select
ste5anSenior DeveloperCommented:
Just a comment: This would be a further code smell/design flaw. Storing a filename in a column designed to store a path..
Mark EdwardsChief Technology OfficerCommented:
@Sam:  Let's not make this anymore complicated than it needs to be.  Misha's formula does what you are looking for, which is to parse the file name from the full path string:


To change a SELECT SQL to an UPDATE SQL, try:

UPDATE [DocsTableName] SET [FilePathFieldName] = Right([DocsTableName].[FilePathFieldName],charindex('\',reverse([DocsTableName].[FilePathFieldName]))-1)

I'll leave it up to you to do whatever other embellishments you want to make to the T-SQL.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.