Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get substring in SQL Server

Tags:

sql-server

I want to get a substring in SQL Server from last sequence of a split on dot (.).

I have a column which contains file names such as hello.exe, and I want to find the extension of the file exactly as Path.GetExtension("filename") does in C#.

like image 757
Rajesh Avatar asked Aug 04 '09 10:08

Rajesh


People also ask

How do I find the substring of a string in SQL Server?

SQL Server CHARINDEX() Function The CHARINDEX() function searches for a substring in a string, and returns the position. If the substring is not found, this function returns 0. Note: This function performs a case-insensitive search.

Can you do a substring in SQL?

SQL Server SUBSTRING() function overviewThe SUBSTRING() extracts a substring with a specified length starting from a location in an input string. In this syntax: input_string can be a character, binary, text, ntext, or image expression.

How do I select the first 3 characters in SQL?

You can use LEN() or LENGTH()(in case of oracle sql) function to get the length of a column. SELECT LEN(column_name) FROM table_name; And you can use SUBSTRING or SUBSTR() function go get first three characters of a column.


2 Answers

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.

like image 103
Eric Avatar answered Sep 21 '22 02:09

Eric


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

like image 36
marc_s Avatar answered Sep 21 '22 02:09

marc_s