Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL text before the Nth match?

Using SQL I'd like to return all text before the 3rd forward slash in a column

so

/one/two/three/whatever/testing

would return:

/one/two/three

Any quick and dirty way to do this in SQL (specifically MS T-SQL under MS SQL 2005+) ?

like image 836
Hell.Bent Avatar asked Feb 06 '12 16:02

Hell.Bent


People also ask

How do I find a string before a specific character in SQL?

To find the index of the specific character, you can use the CHARINDEX(character, column) function where character is the specific character at which you'd like to start the substring (here, @ ).

How do you find the nth occurrence of a character in a string in SQL?

T-SQL's CHARINDEX() function is a useful for parsing out characters within a string.

How do I get all the items left of a character in SQL?

SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).


1 Answers

Since you said "quick and dirty", I'm assuming that this very quick and very dirty solution won't receive a bunch of down votes. The SQL below uses multiple SUBSTRING() functions to find the third slash:

DECLARE @str VARCHAR(50)
SET @str = '/one/two/three/whatever/testing'
SELECT SUBSTRING(@str, 0, CHARINDEX('/', @str, CHARINDEX('/', @str, CHARINDEX('/', @str, CHARINDEX('/', @str, 0) + 1) + 1) + 1))

You can see a working example here.

like image 183
James Hill Avatar answered Sep 30 '22 05:09

James Hill