循环语句中表名的动态变量

时间:2018-06-28 13:02:35

标签: plsql oracle11g

我正在尝试在另一个for循环语句中包含for循环语句,其中内部for循环查询中使用的table_name是第一个for循环的结果:

declare
l_insert_count pls_integer := 0;
begin

for row_outer in (select distinct table_name, item_type from TRANSFORMATION_MAPPING) LOOP
  l_insert_count := 0;


  for row in (select id from ***row_outer.table_name*** where NVL(platnost_do,sysdate)>=sysdate) LOOP

    execute immediate 'insert into ITEM_MAPPING(GUID,ID) VALUES(''CENDB:''' || sys_guid() || ',' || row.id || ')';

    l_insert_count  := l_insert_count + 1;  

    IF (l_insert_count > 999) THEN
        l_insert_count := 0;
        commit;
    END IF;

  END LOOP;

end LOOP;

commit;

end;
/

内部循环的主体要复杂得多。提供的代码仅用于显示我想做什么。 row_outer.table_name 是我想循环执行所需转换的表的变量名。在内部循环中,根据外部循环中的表,我需要在几张不同的表中插入几百万行。

非常感谢:)

1 个答案:

答案 0 :(得分:0)

我把它做成这样(未经测试):

declare
    l_insert_count pls_integer := 0;
    l_detail_cur sys_refcursor;
    l_detail_id integer;
begin
    for r in (
        select distinct table_name, item_type
        from   transformation_mapping
    )
    loop
        l_insert_count := 0;
        l_detail_id := null;

        open l_detail_cur for 'select id from '||r.table_name||' where nvl(platnost_do, sysdate) >= sysdate';

        loop
            fetch l_detail_cur into l_detail_id;
            exit when l_detail_cur%notfound;

            execute immediate 'insert into item_mapping(guid,id) values(''CENDB:''||sys_guid(), :id)' using l_detail_id;

            l_insert_count := l_insert_count + sql%rowcount;

            if l_insert_count > 999 then
                l_insert_count := 0;
                commit;
            end if;
        end loop;

        close l_detail_cur;

    end loop;

    commit;
end;

通常,我会避免提交循环,尤其是对于INSERT(因为它们开销最小且最难以重启),但这取决于您。

相关问题