oracle pl/sql存储过程内外层游标cursor嵌套参数化示例

SQL> select * from acctinactprocess;

                               MEDIUMID                                 ACCTNBR                                VOUCHNBR
--------------------------------------- --------------------------------------- ---------------------------------------
                                      1                                     123                                      12
                                      2                                     222                                      34

SQL> select * from vouchinfo;

                               VOUCHNBR VOUCHNAME
--------------------------------------- ----------
                                     12 VCHE


create or replace procedure proc_nest_cursor
as
cursor cur_acctinactprocess is select mediumid,acctnbr,vouchnbr from acctinactprocess;
v_mediumid ACCTINACTPROCESS.MEDIUMID%type;
v_acctnbr  ACCTINACTPROCESS.Acctnbr%type;
v_vouchnbr ACCTINACTPROCESS.Vouchnbr%type;
v_vouchname vouchinfo.vouchname%type;
cursor cur_vouchinfo(lvsvouchnbr vouchinfo.vouchnbr%type) is select vouchnbr,vouchname from vouchinfo where vouchnbr=lvsvouchnbr;
begin
open cur_acctinactprocess;
loop
  fetch cur_acctinactprocess
  into
      v_mediumid,
      v_acctnbr,
      v_vouchnbr;
  exit when cur_acctinactprocess%notfound;

  dbms_output.put_line('外层循环开始: '||'介质号:'||v_mediumid||' 账号:'||v_acctnbr||' 凭证号:'||v_vouchnbr);

  dbms_output.put_line('内层循环开始');
  --内层游标以外层游标的数据为基础,如果匹配外层游标,就进入内层游标进行处理,如果匹配不上外层游标,不进入内层游标(这个工作,由内层游标的exit when cur_vouchinfo%notfound)
  --以前我理解这种判断机制要用if else来作,看来是多此一举了.
  open cur_vouchinfo(v_vouchnbr);
  loop
      fetch cur_vouchinfo
      into
           v_vouchnbr,
           v_vouchname;
      exit when cur_vouchinfo%notfound;
      dbms_output.put_line('内层循环的值: '||' 凭证号:'||v_vouchnbr||' 凭证名称'||v_vouchname);
  end loop;
  close cur_vouchinfo;
end loop;
close cur_acctinactprocess;
end;


SQL> exec proc_nest_cursor;

外层循环开始: 介质号:1 账号:123 凭证号:12
内层循环开始
内层循环的值:  凭证号:12 凭证名称VCHE
外层循环开始: 介质号:2 账号:222 凭证号:34
内层循环开始

PL/SQL procedure successfully completed


小结:
    业务逻辑的处理流程一定要清晰理解,具体就是多个游标间的逻辑关系:是平行或是父子级别的关系;如果采用平行关系;会导致重复数据的多次打开,减慢效率
    
        游标的参数化一定要好好理解,具体就是游标的参数究竟要几个,以什么为准.这个要和业务理解关联起来.参数化可以让游标的结果是动态化的.游标参数相当
    于where条件,不同的where条件每次输入不同的值,显示结果当然不同了.不就动态了

        实战实战太重要,仅看是远远不够的.先模仿优秀的写法,然后变成自己的,当然这个过程要一些时间了.
    

请使用浏览器的分享功能分享到微信等