简体   繁体   中英

Convert result of CASE Expression to a number in Oracle SQL

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM