Tuesday, June 2, 2009

Parsing filenames with only T-SQL

So from time to time, I get to use SQL functions in a perhaps non-conventional way. Here is one that I love: PARSENAME().

Say I have a column that contains a full path to a file on the filesystem:

ID FilePath
1 MyPath\MyFile.doc
2 MyPath\MyOtherFile.pdf
3 MyPath\MyThirdFile.xls

Let's say I need to know the file extension for those files. Using PARSENAME() will give them to me!

SELECT ID, PARSENAME(filePath,1) as fileExt
FROM myFiles

PARSENAME() will only work on strings with no more than 5 parts -- each part is a substring delimited by a period. The index (1 in the above query) takes the 1st substring starting from the right. You can use PARSENAME() to parse all sorts of things:

File Extensions: PARSENAME('myFile.doc',1) = doc
File Names: PARSENAME('myFile.doc',2) = myFile
Volume Numbers: PARSENAME('7.1.34',3) = 7
Database Objects: PARSENAME('myDb.dbo.myTable.myColumn',2) = myTable

May come in handy for you at some point.

0 comments: