I have the following select
query. I want to convert it from string
into a number
. If I wrap a TO_NUMBER
around the case expression, I get
expression must have same datatype as corresponding expression
error.
SELECT CASE SUBSTR(GRADE, INSTR(GRADE, ' ') + 1) WHEN 'Unspecified' THEN ' ' ELSE SUBSTR(GRADE, INSTR(GRADE, ' ') + 1) END as Final_Grade,
How can I get Final_Grade
to be numeric
?
Thank you!
Advertisement
Answer
Well, ' '
is not a number, so better figure out what to do. I would suggest NULL
:
SELECT (CASE SUBSTR(GRADE, INSTR(GRADE, ' ') + 1) WHEN 'Unspecified' THEN NULL ELSE TO_NUMBER(SUBSTR(GRADE, INSTR(GRADE, ' ') + 1)) END) as Final_Grade,
Actually, I prefer:
(CASE WHEN GRADE NOT LIKE 'Unspecified%' THEN TO_NUMBER(SUBSTR(GRADE, INSTR(GRADE, ' ') + 1)) END) as Final_Grade
Or perhaps even more safely:
(CASE WHEN REGEXP_LIKE(GRADE, '^[0-9]+ ') THEN TO_NUMBER(SUBSTR(GRADE, INSTR(GRADE, ' ') + 1)) END) as Final_Grade