In SQL SERVER 2008 R2, I need to get a count of items contained in a string that can have any of the following characteristics (controlled by the user and not the system):
- each item separated by a comma
- sequential items summarized by the first and last item separated by a dash
- the non-incremental character attached to only the first item in a dash separated range
- multiple characters representing the non-incremental portion of the designation
- combination of the above
All of the following are possible:
- R1,R2,R3,R4
- R1-R4
- R1-4
- CP10-CP12
- R1,R15-R19,RN5
If they were all comma separated, I could just count the commas +1, but that is actually less common than the other options.
A method to count the last option should work for all options. The result should be 7
My expected approach would be to:
- separate the items without a dash but separated by a comma => get a count
- isolate the dash separated items and remove the non-incremental character(s)
- subtract the smaller number from the larger number and add 1
- Add that number to the first number for a total count
I am totally stuck on even where to begin. Any ideas?
This can be cleaned up/optimized and is intentionally verbose but should get you started. Notably, the logic inside the last IF is almost identical to that of the WHILE and the block that gets the numeric value of the left/right elements is repeated four times.
Outputs the following results: