PL / SQL Proc性能调整

问题描述

我在proc内有一个循环,循环一个ID。 CDID可以有4种类型:

CDID      TYPE
123     AA
456     BB
789     CC
999     DD

每种类型的IF有4个主要块。尽管CDID不必具有全部4种类型,并且每个主IF块都由嵌套的if块组成。 在嵌套的ifs中,我使用选择查询将值插入4个变量(不是表)中。在所有4个IF块的末尾,只有一条update语句,它接收4个变量的值并更新表。

下面是供您参考的proc结构:

CREATE OR REPLACE PROC MY_PROC
a varchar2;
b varchar2;
c varchar2;
d varchar2;
v_cnt number
BEGIN
FOR I IN (SELECT CDID FROM TABLE_A where column is null)    --this table contains only 1 row for each id
BEGIN
    select count(*) into v_cnt from TABLE_B where cdid=i.cdid and type='AA';
    if v_count > 0 then
        nested ifs
        SELECT a,b,c,d INTO a,d from TABLE_B where cdid=i.cdid and type='AA'...;
        end ifs...;

    if v_count = 0 then --if count is zero of TYPE:AA

    select count(*) into v_cnt from TABLE_B where cdid=i.cdid and type='BB';  
    if v_count > 0 then
       nested ifs
       select a,d from TABLE_B where cdid=i.cdid and type='BB'...;
       end ifs...;

    if v_count = 0 then --if count is zero of TYPE:BB
        same thing continues for TYPES CC AND DD.
    end if;
END;
UPDATE TABLE_A
SET COLUMN1=A,COLUMN2=B,COLUMN3=C,COLUMN4=D
where cdid=i.cdid;
END LOOP;
END;

大约30k-35k记录,执行此过程需要40分钟。在上面的过程中,对于每个cdid,它可以检查多个if。

我无法确定如何对该过程进行微调。如何批量处理记录?

解决方法

未经测试,但根据@GloezTrol在评论中所说的内容,下面的内容应该可以工作。使用按类型排序的单个游标,以便它以正确的顺序处理IF。然后循环直到找到所需的记录并退出。

CREATE OR REPLACE PROC MY_PROC as
a varchar2(10); -- size these appropriately
b varchar2(10);
c varchar2(10);
d varchar2(10);
v_cnt number;

cursor loop_cur is
select *
from TABLE_B 
where cdid=i.cdid
and type in ('AA','BB','CC','DD')
order by type asc;

BEGIN
  FOR I IN (SELECT CDID FROM TABLE_A where column is null)    --this table contains only 1 row for each id
    BEGIN
      -- good practice to re-initialize variables at start of loop
      a := null;
      b := null;
      c := null;
      d := null;

      for v_row in loop_cur loop
        if v_row.type = 'AA' then
          nested ifs
            a := v_row.a;
            b := v_row.b;
            c := v_row.c;
            d := v_row.d;
            exit; -- get out of the loop if there was a 'AA' 
          end ifs...;
         if v_row.type = 'BB' then
           nested ifs
             a := v_row.a;
             b := v_row.b;
             c := v_row.c;
             d := v_row.d;
             exit; -- get out of the loop if there was a 'BB' 
           end ifs...;
         end if
         repeat for 'CC' and 'DD'
       end loop;
     END;
    UPDATE TABLE_A
    SET COLUMN1=A,COLUMN2=B,COLUMN3=C,COLUMN4=D
    where cdid=i.cdid;
  END LOOP;
END;