Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get everything after and before certain character in SQL Server

Tags:

sql

sql-server

I got the following entry in my database:

images/test.jpg 

I want to trim the entry so I get: test

So basically, I want everything after / and before .

How can I solve it?

like image 519
ffffff01 Avatar asked Jun 13 '12 07:06

ffffff01


2 Answers

use the following function

left(@test, charindex('/', @test) - 1) 
like image 89
baljeet Singh Avatar answered Sep 18 '22 10:09

baljeet Singh


If you want to get this out of your table using SQL, take a look at the following functions that will help you: SUBSTRING and CHARINDEX. You can use those to trim your entries.

A possible query will look like this (where col is the name of the column that contains your image directories:

SELECT SUBSTRING(col, LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) + 1,      LEN(col) - LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) - LEN(SUBSTRING(     col, CHARINDEX ('.', col), LEN(col)))); 

Bit of an ugly beast. It also depends on the standard format of 'dir/name.ext'.

Edit:
This one (inspired by praveen) is more generic and deals with extensions of different length:

SELECT SUBSTRING(col, LEN(LEFT(col, CHARINDEX ('/', col))) + 1, LEN(col) - LEN(LEFT(col,      CHARINDEX ('/', col))) - LEN(RIGHT(col, LEN(col) - CHARINDEX ('.', col))) - 1); 
like image 29
Josien Avatar answered Sep 18 '22 10:09

Josien