在某条件下的表的某项求和,为了避免no data found exception,我一般都会先查一下是否存在记录:
select count(*)
into c
from t1
where t1.xx = '22012';然后再求和:
if c > 0 then
select sum(t1.op)
into s
from t1
where t1.xx = '22012';
end if;但如果t1是具有2亿多行的表,那么两次查询就不太必要了,是否可以一次完成?此前看到有人提到用exception when ...处理,但Oracle的exception 只能写在存储过程的后部,要用exception 会对存储过程有很大的改动,而且还有其它表也需要作同样处理。那么请问大家是如何处理的呢?

解决方案 »

  1.   


    with t1 as
    (
         select 1 c1 from dual
         union all
         select 2 c1 from dual
         union all
         select 3 c1 from dual
    ) select case when count(*)<>0 then sum(c1) else 0 end case
    from t1
    where t1.c1=4
      

  2.   

    我还是觉得exception是个比较好的处理方案
    如果你们项目允许的话
      

  3.   

    你直接求和有问题?
    select sum(t1.op)
    into s
    from t1
    where t1.xx = '22012';
      

  4.   

    select nvl(sum(t1.op),0)
    into s
    from t1
    where t1.xx = '22012';
    这样的话,如果没有数据,s就是0,你可以试试另外 你给的例子 如果没有数据 也不会报错的 因为sum本身就是聚合函数
      

  5.   


    我没说清楚,应该是“在存储过程中对查询结果可能为空的表的统计处理”,用case也会报no_data_exception。谢谢。
      

  6.   


    我没说清楚,应该是“在存储过程中对查询结果可能为空的表的统计处理”,直接求和会报no_data_exception。谢谢。
      

  7.   


    我没说清楚,应该是“在存储过程中对查询结果可能为空的表的统计处理”,如果查询没有数据,用sum会报no_data_exception。谢谢。
      

  8.   

    试过吗?
    select sum(t1.op)
    into s
    from t1
    where t1.xx = '22012';
    上面是不会抛no_data_found的。
      

  9.   

    一 'no data found exception',这个例外是用在select .. into ..时的,当select 没有值时,会报这个例外
    二 按照我的理解,你完全没有必要用select ..into..语句
      case when   t1.xx = '22012' then sum(t1.op)
        else 0 end
      

  10.   


    谢谢,case when我也想过,不过我凑了很久没有凑对格式,请问应该如何写全这个select case when?
      

  11.   

    select sum(xxx) from ttt 如果没有group by,它永远不会报no_data_found,最多需要加个nvl函数
    select sum(xxx) from ttt group by yyy 这个可能报错,一个最简单的decode就完事了。
      

  12.   

    相较之下 还是decode函数比较靠谱 性能也可以
      

  13.   

      SELECT t1.xx,case when   t1.xx = '22012' then sum(t1.op)
        else 0 END
      FROM t1
      GROUP BY  t1.xx