I have the following SQL query:
SELECT DISTINCT ProductNumber, PageNumber FROM table
I am trying to modify the query so that PageNumber will be formatted. You see, PageNumber is in any of the following formats, where ‘x’ is a digit:
- xxx, xxx
- xxx
- xxx-xxx
- xx, xxx-xxx
- xx-xx, xxx
- xx-xx, xxx-xxx
I want to format PageNumber so that it is only in the format: xxx. To do so, I have parse out the following bolded numbers from the above formats:
- xxx, xxx
- xxx
- xxx-xxx
- xx, xxx-xxx
- xx-xx, xxx
- xx-xx, xxx-xxx
I want to do this all without writing any functions, but I don’t know if that is possible. I am having trouble “detecting” all of the different formats, though:
Here is what I have so far:
SELECT ProductNumber,
CASE WHEN CHARINDEX(',', PageNumber) > 0
THEN SUBSTRING(PageNumber, 0, CHARINDEX('-', PageNumber))
WHEN CHARINDEX('-', PageNumber) > 0
THEN SUBSTRING(PageNumber, 0, CHARINDEX('-', PageNumber))
ELSE PageNumber
END AS PageNumber
FROM table
WHERE PageNumber IS NOT NULL
AND PageNumber <> ''
Can anyone offer me some help? Thanks!
Use pattern matching rather than CHARINDEX
CASE also forces ordering of evaluation which helps here for the 3rd case which overlaps with the first 2 cases.
Not tested, something like