0

I'm trying to use Case Statement for the following

 SELECT .. to_number(nvl(il.var1,0)) * to_number(nvl(il.var2,0)) * to_number(nvl(il.var3,0))/1000000 AS calculated_value,

Sometimes, either var1 or var2 or var3 will have alphabets inside(dirty data) in which my query will return an error.

How do I structure my query with case statement in which if the result of the equation does not return me valid numeric or if var1 | var2| var3 is not integer, set calculated_value as "0" or "Empty" for that row only?

2
  • Dirty data? So why are these columns strings in the first place? With an appropriate column data type there would be no problem at all. Commented Feb 1, 2018 at 10:05
  • If you are on Oracle 12.2 or can upgrade to it, you can use the default n on conversion error parameter to to_number. Commented Feb 1, 2018 at 10:45

2 Answers 2

1

Try to check whether those VARx really are numbers. For example:

from ...
where regexp_like(il.var1, '^\d+$')
  and regexp_like(il.var2, '^\d+$')
  and regexp_like(il.var3, '^\d+$')

[EDIT] Aha, you'd still want to get some result.

Then you'd use something like this: if VARx isn't a number, use "0" (zero) and the final result will be 0.

select case when not regexp_like(il.var1, '^\d+$') then 0
            else il.var1
       end
       *
       case when not regexp_like(il.var2, '^\d+$') then 0
            else il.var2
       end
       as result
from ...
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, what is the purpose of the *, im getting syntax errors.
Multiplying, as that's what I saw you doing.
1
  SELECT 
  CASE WHEN ((REGEXP_LIKE (il.var1,'^-?\d+(\.\d+)?$')
              OR  (REGEXP_LIKE (il.var2,'^-?\d+(\.\d+)?$') 
              OR (REGEXP_LIKE (il.var3,'^-?\d+ (\.\d+)?$'))
       THEN 0
  ELSE
     to_number(nvl(il.var1,0)) * to_number(nvl(il.var2,0)) * to_number(nvl(il.var3,0))/1000000 AS calculated_value

2 Comments

Hm, that should be vice versa, shouldn't it? As you put it, the result will be 0 if VARx are numbers.
^ Yes, my fields are now all 0

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.