oracle 函数中,一定要注意出现空记录和多条记录的处理方法

今天折腾了3个小时,为一个以前不知道的oracle函数机制:

在sql查询中,如果一个查询未能获取记录,oracle不会报错

如select aa from bb where 1=2;

但在oracle函数中,如果是赋值语句,就会报错ORA-01403: no data found 数据未找到

如select aa into kk from bb where 1=2;

今天的错误就在这里,主要是弄混了字段null和记录为空的null,而且是在递归调用中,sql的断点调试其实是直接进入了最后一层递归,所以第一步就报错。而用sql检查只检查出第一步有值。

所以迷惑了半天。

解决函数中空记录报错的方法最好是用count(*)判断,通过截获报错Exception的方法一直提示没有返回值,没找到原因

用count(*) 时注意,sql自动进入了单分组模式,所有字段都必须用min,max等。 

create or replace function rteseg_seq(retseg_uuid in varchar2)

return number is

res_seg_uuid varchar2(36); 

begin

  select decode(count(*),1,min(rsg1.route_segment_uuid),null ) into res_seg_uuid --首先判断是否有记录,如果没有直接赋值null给变量res_seg_uuid,否则就正常赋值,注意min其实无意义,只是sql语法要求

  from ROUTE_SEGMENT_TS rsg1, ROUTE_SEGMENT_TS rsg2

  where rsg1.route_uuid = rsg2.route_uuid 

  and rsg1.end_point_id=rsg2.start_point_id 

  and rsg2.route_segment_uuid = retseg_uuid;

 

  if res_seg_uuid is null then return 1;

  else

    return rteseg_seq(res_seg_uuid)+1;

    end if;

 

end;

 

posted on 2017-11-22 12:48  mol1995  阅读(595)  评论(0编辑  收藏  举报

导航