How can I split a column data in sql. If hyphen is present, Only display the data before the hpyhen.
Asked
Active
Viewed 50 times
0
-
can you provide some examples of what the inputs are and what the outputs should be? – user156213 Aug 18 '15 at 22:01
-
1I 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 Answers
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,242,037
- 58
- 646
- 786
2
select substring(colname, 1, charindex('-',colname)-1)
from tablename
You can use a combination of substring
and charindex
.

Vamsi Prabhala
- 48,685
- 4
- 36
- 58