使用游标循环,插入并提交每一行的更有效方法(Oracle)

时间:2019-03-19 09:26:19

标签: loops cursor commit bulk-collect

我在下面写了这样的东西(它可以工作),但是就我而言,对于1,5百万行,它的效率不是我所需要的(可能要运行2天) 我看到了类似BULK COLLECT FETCH FORALL之类的东西,但是我没有设法将我的代码重写为没有错误。你能帮我吗?

谢谢

--It is my code for rewriting
    DECLARE
      cnt NUMBER;
      d_min NUMBER;
      d_max NUMBER;
      i NUMBER := 0;
      CURSOR ts_metatata_cur IS select * from (select rownum as rn, id_profile from ts_metadata where typ=7 and per=3600 order by id_profile) where rn between 1 and 100000;
    BEGIN
      for metadata_rec in ts_metatata_cur
      LOOP
            XTS.GET_PROFILE_AGGR(metadata_rec.id_profile, cnt, d_min, d_max);    --procedure with one IN parameter and three OUT parameter cnt, d_min, d_max
            Execute immediate 'insert into TMP_PROFILES_OVERVIEW (id_profile, cnt, d_min, d_max) values (' || metadata_rec.id_profile || ', ' || cnt || ', ' || d_min ||  ', ' || d_max ||')';
            i := i+1;
            if (i > 10000) then
              commit;
              i := 0;
            end if;
      END LOOP;
    commit;
    END;

如果有必要,我在这里给我打电话的程序:

--this is procedure, which I call in my script
CREATE OR REPLACE PROCEDURE XTS.GET_PROFILE_AGGR(id_prof IN NUMBER, cnt OUT NUMBER, d_min OUT NUMBER, d_max OUT NUMBER)
AS 
  res varchar2(61);
BEGIN
  select cluster_table_name into res FROM XTS.TIME_SERIES TS where TS.id=id_prof;
  Execute immediate 'select nvl(count(*),0), nvl(min(time),0), nvl(max(time),0) from '|| res || ' where time_series_id=' || id_prof || ' ' into cnt, d_min, d_max;

EXCEPTION

  when others then
  null;

END;

1 个答案:

答案 0 :(得分:0)

在别人的建议下,我改变了工作方式。我只将分组数据插入,而不是每行插入。

类似这样的东西:

创建或替换过程XTS.GET_PROFILE_AGGR
    AS
      CURSOR time_series_cur IS从xts.time_serie中选择不同的cluster_table_name作为res;

BEGIN  
  for time_series_rec in time_series_cur  
  LOOP  
    Execute immediate 'INSERT INTO HDO.tmp_profiles_overview (id_profile, cnt, d_min, d_max) select time_series_id, count(*), min(time), max(time) from ' || time_series_rec.res || ' group by time_series_id';  

  END LOOP;  

commit;   
END;