Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Get File Extension Name from a Column

Tags:

I have a table with a column that contains the entire file name, the data looks like:

FilePath                       FileSize
------------------------------ --------
dsch2_chs_wyj.rar              694KB
AllInOneHash.rar               19KB
FilePropertyModifier.rar       12KB
jquery_1_7_api_chm_chs.rar     285KB
startupmgr.rar                 38KB
JQueryTableExample_Edi.rar     33KB
hdpartioncalc_csharp.rar       49KB
XMLMenuTest.zip                3KB

Now I want to extract the file extension name, like .rar and insert into a new table.

INSERT INTO Attachment
  (
    Id,
    [FileName],
    ExtensionName,
    StoredPath,
    CreateOn,
    UploaderIP,
    DataBinary
  )
SELECT ba.Id,
       ba.Title,
       '{Extension Name}',
       ba.FilePath,
       GETDATE(),
       NULL,
       NULL
FROM   BlogAttachment ba

But T-SQL doesn't have a LastIndexOf() function. How can I cut the substring in an easy way?

like image 838
Edi Wang Avatar asked May 28 '13 02:05

Edi Wang


People also ask

How do I get the file extension in SQL?

In order to get file extension of file as a result of SQL query, you can use SUBSTRING_INDEX(). Insert some records in the table using insert command. Display all records from the table using select statement.

How do I find a file in SQL?

If you ever need to know where your database files are located, run the following T-SQL code: USE master; SELECT name 'Logical Name', physical_name 'File Location' FROM sys. master_files; This will return a list of all data files and log files for the SQL Server instance.

How do you name a file in SQL?

SQL Server does not enforce any particular naming standard for files. SQL Server is perfectly happy with a data file named “readme. txt” or a log file named “word. doc”.


2 Answers

You can get the extension by doing:

 select reverse(left(reverse(FilePath), charindex('.', reverse(FilePath)) - 1))

However, I would recommend that you check that there is a '.' in the name first:

 select (case when FilePath like '%.%'
              then reverse(left(reverse(FilePath), charindex('.', reverse(FilePath)) - 1))
              else ''
         end) as Extension
like image 142
Gordon Linoff Avatar answered Oct 02 '22 08:10

Gordon Linoff


SELECT CASE 
         WHEN filepath LIKE '%.%' THEN RIGHT(filepath, Len(filepath) - 
                                                       Charindex('.', filepath)) 
         ELSE filepath 
       END FilePath 
FROM   tbl1 

Demo

like image 43
Kermit Avatar answered Oct 02 '22 10:10

Kermit