Oracle数据库存储过程--使用游标(3)

[size=small]select into不可乎视的问题 [/size]

我们知道在pl/sql中要想从数据表中向变量赋值,需要使用select into 子句。
但是它会带动来一些问题,如果查询没有记录时,会抛出no_data_found异常。
如果有多条记录时,会抛出too_many_rows异常。
这个是比较糟糕的。一旦抛出了异常,就会让过程中断。特别是no_data_found这种异常,没有严重到要让程序中断的地步,可以完全交给由程序进行处理。
For Exaple:
create or replace procedure procexception(p varchar2)
as
  v_postype varchar2(20);
begin
   select pos_type into v_postype from pos_type_tbl where 1=0;
    dbms_output.put_line(v_postype);
end;

处理这个有三个办法
1. 直接加上异常处理。 (这样做换汤不换药,程序仍然被中断。可能这样不是我们所想要的。 )
create or replace procedure procexception(p varchar2)
as
  v_postype varchar2(20);
 
begin
   select pos_type into v_postype from pos_type_tbl where 1=0;
    dbms_output.put_line(v_postype);
exception
  when no_data_found then
    dbms_output.put_line('没找到数据');
end;

2. select into做为一个独立的块,在这个块中进行异常处理 (这是一种比较好的处理方式了。不会因为这个异常而引起程序中断。 )
create or replace procedure procexception(p varchar2)
as
  v_postype varchar2(20);
 
begin
  begin
   select pos_type into v_postype from pos_type_tbl where 1=0;
    dbms_output.put_line(v_postype);
exception
  when no_data_found then
    v_postype := '';
  end;
  dbms_output.put_line(v_postype);
end;

3.使用游标(这样就完全的避免了no_data_found异常。完全交由程序员来进行控制了。 )
create or replace procedure procexception(p varchar2)
as
  v_postype varchar2(20);
  cursor c_postype is select pos_type  from pos_type_tbl where 1=0;
begin
  open c_postype;
    fetch c_postype into v_postype;
  close c_postype;
  dbms_output.put_line(v_postype);
end;


猜你喜欢

转载自lilongping269.iteye.com/blog/1334979