0

How can I split a column data in sql. If hyphen is present, Only display the data before the hpyhen.

user793468
  • 4,328
  • 22
  • 74
  • 120
  • can you provide some examples of what the inputs are and what the outputs should be? – user156213 Aug 18 '15 at 22:01
  • 1
    I think the word you're looking for is "split." That said, this is why you should normalize your data. Anything that can be derived as the combination of 2 things should almost always be stored as the two things separately (because it's harder to pull them apart correctly than it is to put them back together). – jpmc26 Aug 18 '15 at 22:04

2 Answers2

3

You need to be careful to test if a hyphen is present. This should work:

select left(colname, charindex('-', colname + '-') - 1)

If you don't do the "append an extra hyphen trick" then you need conditional logic (such as a case statement).

Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624
2
select substring(colname, 1, charindex('-',colname)-1)
from tablename

You can use a combination of substring and charindex.

Vamsi Prabhala
  • 46,335
  • 4
  • 30
  • 47