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+) ?
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, @ ).
T-SQL's CHARINDEX() function is a useful for parsing out characters within a string.
SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With