-1

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!

5
  • CAST or CONVERT = learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/… - stackoverflow.com/questions/728833/… Commented Feb 13, 2020 at 14:44
  • Does this answer your question? Convert a string to int using sql query Commented Feb 13, 2020 at 14:45
  • use TO_NUMBER( string1 [, format_mask] [, nls_language] ) and replace WHEN 'Unspecified' THEN ' ' with WHEN 'Unspecified' THEN -1, or any other number that make sense Commented Feb 13, 2020 at 14:47
  • How are your data samples? Do you want to extract digits from a string(GRADE)? Why do you need space characters? Btw, a case..when expression cannot start in such a way like CASE SUBSTR(GRADE, INSTR(GRADE, ' ') + 1) .. Commented Feb 13, 2020 at 15:00
  • Seems like GRADE contains non-numeric data. If you can't figure it out please post a reproducible test case including sample data. Commented Feb 13, 2020 at 15:01

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.