Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

File Name Parsing Calculations - SQL Server

RSS
Modified on Wed, Jan 25, 2012, 9:00 AM by Administrator Categorized as SQL Server

Overview

Given a database table with a column containing a fully-qualified file name (full path + file name + file extension), we want to parse out the file extension and the file name without the extension.

Solution

The following code assumes the table is called ImageFile and the fully-qualified file name is in the FullFileName column. It requires that you have two auxiliary INT columns: LastSlashPos and LastDotPos.

PITFALL: This code assumes that the only period is for the file extension — i.e., that none of the folders in the file's path contain a period.

update 
    dbo.ImageFile
set
     LastSlashPos = len(FullFileName) - charindex('\', reverse(FullFileName)) + 1
    ,LastDotPos   = len(FullFileName) - charindex('.', reverse(FullFileName)) + 1
-----------------------------
update 
    dbo.ImageFile
set
     FileExtension      = substring(FullFileName, LastDotPos+1,Len(FullFileName))
     FileNameWithoutExt = substring(FullFileName, LastSlashPos+1, LastDotPos-LastSlashPos-1)

User-Defined Function

The following function returns the file extension (including the leading period) of the file specified.

/*
select result = dbo.udsFileExtension('hello.vbs.txt.xml')
*/
ALTER function [dbo].[udsFileExtension]
    (
    @file varchar(max)
    ) returns varchar(max) as begin

declare 
     @result varchar(max)
    ,@pos int

select 
     @pos       = len(@file) - charindex('.', reverse(@file)) + 1
    ,@result    = case 
                    when @file like '%.%' then substring(@file, @pos, len(@file)) 
                    else '' 
                    end

return @result

end

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.