Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on only first occurance of character/delimiter

I've been searching all morning for this.

My knowledge of SQL Server is not excellent, and I'm out of answers.

Concrete examples are: City-Of-Style or Part1-Part2.

I need to split these examples into City and Of-Style and Part1 and Part2.

I figured out this little piece of code, but it switches part1 and part2 if the string contains a '-'.

PARSENAME(REPLACE('sample-string', '-', '.'), 1))

Any help on accomplishing this (preferably without a 200 lines function) is greatly appreciated.

like image 504
voluminat0 Avatar asked Nov 17 '12 13:11

voluminat0


1 Answers

If I understand correctly this will do the job; Click here for the fiddle

DECLARE @s VARCHAR(50)= 'City-Of-Style'

SELECT SUBSTRING(@s,0,CHARINDEX('-',@s,0)) AS firstPart,
    SUBSTRING(@s,CHARINDEX('-',@s,0)+1,LEN(@s)) AS secondPart
like image 124
Kaf Avatar answered Sep 18 '22 15:09

Kaf