Let me summarize a bit:
I didn't simply gave you a final solution but the single steps to show you how you arrive there, I warned about the possible problems, one really happened and you even didn't notice and had no idea what to do.
I know people are typically only telling the regular case, but programming could be much easier, if that typical case wouldn't be accompanied by corner cases. You have a few possible corner cases here and data without a dash is only one corner case.
Nobody can browse more than a few rows, so use SQL to get an overview:
Code:
SELECT CHARINDEX('-',field) as DashPosition, Count(*) as Howoften FROM yourtable GROUP BY CHARINDEX('-',field)
Seeing a row with 0 as Dashposition data without a dash is revealed.
Even more cautious would be first trying with some self generated test data about expected wrong data:
Code:
Declare @yourtable as Table (field char(10) null)
insert into @yourtable values ('a-1'),('b4'),(null)
SELECT CHARINDEX('-',field) as DashPosition, Count(*) as Howoften FROM @yourtable GROUP BY CHARINDEX('-',field)
We see CHARINDEX('-',NULL) is fortunately not erroring, simply resulting in NULL. And that also gives us an overview about corner cases of NULL aside of data with no dash. Now what about data with more than one dash?
Code:
Declare @yourtable as Table (field char(10) null)
insert into @yourtable values ('a-1'),('b-4-v'),(null)
SELECT LEN(field)-LEN(REPLACE(field,'-','')) as NumberOfDashes, Count(*) as Howoften FROM @yourtable GROUP BY LEN(field)-LEN(REPLACE(field,'-',''))
You got to be a detective and determined to reach your goal as programmer. If you don't get any ideas how to use your programming skills to see whether your customer lied to you by only telling the regular case, then you can be replaced by any other developer. It's not, that customers lie by intention, they just don't think to the end, have no overview. That's your chance to earn money. You have overview, you could have, if you just do a little analysis before jumping to the task. You're not determined enough, if you don't use that.
You got more than "any help", even just by being pointed to functions by John, they are documented and you can read. Just answering you tried that functions is so typical. Then show, what you tried, and we see your deficits. Are you afraid to show deficits? Then you never will learn, what you don't discover on your own. Just seeing your wrong understanding of how functions work we can put you on the right track interactively. The help text won't answer questions.
Common, have you forgotten about the fun to find a solution? Is this a burden for you? Then how about looking for something else than programming?
Bye, Olaf.