Sql-server – Getting filename with out extension using SQL query in SQL server

sql servertsql

I have an issue while getting the file name with out extension from a column in SQL table like this.

The column name is [image] in dbo.emp table and the values are:

temp.jpg
test1.jpg
test1.jpeg
sample.jpg
sample1.gif

Now I want to get only temp, test1, sample, sample1 without the extension .jpg, .jpeg, etc…

Best Answer

DECLARE @x VARCHAR(32);
SET @x = 'temp.jpg';
SELECT SUBSTRING(@x, 1, CHARINDEX('.', @x)-1);
-- or SELECT LEFT(@x, CHARINDEX('.', @x)-1);

Result:

temp

This doesn't specify what to do if a . is not found, however. If you want to deal with that and return th whole string when no . is found:

DECLARE @x TABLE([image] VARCHAR(32));
INSERT @x SELECT 'temp.jpg' UNION ALL SELECT 'sample1.gif' UNION ALL SELECT 'foo';
SELECT SUBSTRING([image], 1, COALESCE(NULLIF(CHARINDEX('.', [image]),0)-1, 32)) FROM @x;

Results:

temp
x
foo