简体   繁体   中英

Handling empty or null values In SELECT statement using case

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?

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 ...
  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

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