tags:

views:

589

answers:

2

Hi Guys,

I want to get substring in sql server from right split on dot('.').

I have a column which have file name hello.exe , i want to find extension of file exactly as in C# Path.GetExtension("filename") does.

Thanks Rajesh

A: 
DECLARE @originalstring VARCHAR(100)
SET @originalstring = 'hello.exe'

DECLARE @extension VARCHAR(50)

SET @extension = SUBSTRING(@originalstring, CHARINDEX('.', @originalstring) + 1, 999)

SELECT @extension

That should do it, I hope! This works as long as you only have a single '.' in your file name - separating the file name from the extension.

Marc

marc_s
+4  A: 

You can use reverse along with substring and charindex to get what you're looking for:

select
    reverse(substring(reverse(filename), 1, 
        charindex('.', reverse(filename))-1)) as FileExt
from
    mytable

This holds up, even if you have multiple . in your file (e.g.-hello.world.exe will return exe).

So I was playing around a bit with this, and this is another way (only one call to reverse):

select 
    SUBSTRING(filename, 
        LEN(filename)-(CHARINDEX('.', reverse(filename))-2), 8000) as FileExt
from
    mytable

This calculates 10,000,000 rows in 25 seconds versus 29 seconds for the former method.

Eric
+1 good call ! I was wondering if there way any easy way to deal with multiple '.' in the file name, without resorting to messy character counting and parsing - well done!
marc_s
charindex('.', reverse(filename))-1 fails when there is no dot in filename. used charindex('.', reverse(filename))
Rajesh