Oracle中除数为0的两种解决办法(decode与nullif)

Oracle中Decode函数,语句DECODE(tag,''ZCGS'',0,1)=decode(''@corp-No@'',''6010'',1,0)

decode(字段或字段的运算,值1,值2,值3)
这个函数运行的结果是,当字段或字段的运算的值等于值1时,该函数返回值2,否则返回值3
当然值1,值2,值3也可以是表达式,这个函数使得某些sql语句简单了许多

1.decode
利用decode函数:

select decode(b,0,0,a/b) from dual;
1
当b = 0时,返回0,否则才返回a/b的结果。

2.nullif
先来说一下nullif的语法。

nullif(expr1,expr2)
1
如果两个参数相等,返回null,否则返回第一个。第一个参数不可指定为空。对于非数字类型参数,数据类型必须一致。对于数值数据类型,会隐式的转化为更高优先级的数据类型。(这个理解可能有误,我测试了int,integer,float。但是最终都转化为number类型)。

一般来说,我们处理“除数为零”的问题会用到decode(当然也可以用case,但是写起来代码更多些)。比如

dividend / decode(divisor, 0, null, divisor)
1
但是在除数divisor非常复杂的时候,就需要把这一大串代码写两遍,或者是再套一层view。无论是哪种,都是极其不利于维护的。

1 / 
decode((sum(t.val) over(order by t.c) +
       nvl(lead(val) over(partition by b order by c), 0)) /
      sum(val) over(partition by b order by c),
      0,
      null,
      (sum(t.val) over(order by t.c) +
       nvl(lead(val) over(partition by b order by c), 0)) / sum(val)
      over(partition by b order by c))

对于这种复杂表达式的除数,每回修改都要改两遍,很容易出错。

利用nullif,可以让除数只写一次。
因为 decode(divisor, 0, null, divisor) 与 nullif(divisor, 0) 是等效的。
 
原文地址:https://www.cnblogs.com/xianz666/p/13073664.html