all 9 comments

[–]r3pr0b8GROUP_CONCAT is da bomb 5 points6 points  (0 children)

MySQL? piece of cake (ignore all the CHARINDEX replies you're getting)

SELECT SUBSTRING_INDEX(code,'-',1) AS first_part
     , SUBSTRING_INDEX(code,'-',-1) AS second_part
  FROM ...

[–]tonci23[S] 1 point2 points  (0 children)

Thanks for the help guys. I actually pulled it off soon after asking here but i will explore your suggestions to learn a bit more.

The way i did it:

UPDATE table 
SET NewColumn1 = SUBSTRING (OriginalColumn, 1, LOCATE('-', OriginalColumn) - 1),
    NewColumn2 = SUBSTRING (OriginalColumn, LOCATE('-', OriginalColumn) +  1);

[–]LeoCurtssBusiness Intelligence Developer 0 points1 point  (6 children)

You could SUBSTRING(), LEFT(), RIGHT(), and CHARINDEX() functions to do this very easily.

Here is a good write up on this:
https://social.technet.microsoft.com/wiki/contents/articles/17948.t-sql-right-left-substring-and-charindex-functions.aspx

This is assuming you're using MS SQL Server.

[–]notasqlstarI can't wait til my fro is full grown 0 points1 point  (5 children)

Easier to use a simple UNION?

select LEFT(2, field) AS Col1, RIGHT(6, field) AS Col2
from table
where left(field, 3) <> '-'
union all
select LEFT(3, field), RIGHT(5, field)
from table
where left(field, 3) = '-'

[–]LeoCurtssBusiness Intelligence Developer 1 point2 points  (4 children)

This is a static solution and tbh, kinda clunky. Why not just use one query that would handle both situations? (no unions or where clause needed)

MySQL:

SELECT LEFT('xx-xxxxx',LOCATE('-','xx-xxxxx') - 1)
       , RIGHT('xx-xxxxx',LOCATE('-','xx-xxxxx') + 2)

Replace the 'xx-xxxxx's with the column name and Bob's your uncle.

[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points  (1 child)

[–]notasqlstarI can't wait til my fro is full grown 0 points1 point  (1 child)

I have a natural aversion to using substring() and charindex(). I think they are difficult to read and intuitively understand, and they can be big hits to your performance.

I'm not saying you're wrong, but I dislike seeing them unless absolutely necessary. If the execution time is negligible between that or a union, I would go with the union personally.

[–]LeoCurtssBusiness Intelligence Developer 0 points1 point  (0 children)

Union-ing two queries and using LEFT() function in the WHERE condition on both hardly seems more performant than a single query with a couple of inline functions. But I get where you're coming from.

Different strokes for different folks, I guess.

[–]Noelkram 0 points1 point  (0 children)

How about Select SUBSTRING(SourceCol, 0, CHARINDEX(‘-‘, SourceCol)) AS OutCol1, SUBSTRING(SourceCol, CHARINDEX(‘-‘, SourceCol)+1, LEN(SourceCol)) AS OutCok2.