Boris is right about the . in the file name.
Let's look at this part of the code.
REVERSE(LEFT(REVERSE(filename), CHARINDEX('.', REVERSE(filename))-1))
For talking purposes, let's remove the REVERSE function.
LEFT(filename, CHARINDEX('.', filename)-1)
Now, suppose there are no dots in the filename. In this situation, the charindex function would return 0.
LEFT(filename, 0-1)
Which is the same as
LEFT(filename, -1)
When I run this on my SQL instance, I get:
[red]Invalid length parameter passed to the left function.[/red]
I know that previous versions of SQL Server mentioned the substring function when passing a negative value to the left (or right) function.
This situation is easy enough to accommodate:
Code:
Select NullIf(REVERSE(LEFT(REVERSE(FileName), CHARINDEX('.', REVERSE('.' + FileName))-1)), FileName) AS Extension,
Count(*) As ExtensionCount
From YourTable
Group By NullIf(REVERSE(LEFT(REVERSE(FileName), CHARINDEX('.', REVERSE('.' + FileName))-1)), FileName)
Notice a couple changes made to Boris's code.
REVERSE('.' + FileName)
I added a '.' to the front of the filename. When this is reversed, the dot will be at the end. The CharIndex function will return the first dot, so having a dot on the end will only make a difference if there is no dot at all in the filename. This means that when there is no dot in the file name, this code will return the entire filename as though it were an extension.
To accommodate this, I used the nullif function, so we basically have this...
NullIf(Big long ugly looking code, filename) As Extension
Basically, if the "big long ugly code" returns the entire string, the nullif function compares it to the original string. If it's the same, NULLIF will return NULL. So... this code will return a filename extension if it exists or NULL otherwise.
Make sense?
-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom