Oracle将结果集放入FORALL中的变量中

问题描述 投票:0回答:1

我有以下plsql块

declare 
    TYPE t_mds_ids IS TABLE OF mds.id%TYPE;
    l_mds_ids t_mds_ids;
    l_mds_parents t_mds_parents;
begin
    SELECT id BULK COLLECT INTO l_mds_ids FROM mds;
    FORALL indx IN l_mds_ids.FIRST .. l_mds_ids.LAST
        select l_mds_ids(indx), ch.id_employee_parent
        into l_mds_parents
        FROM hierarchy_all ch
        CONNECT BY ch.id_employee = prior ch.id_employee_parent
        START WITH ch.id_employee = l_mds_ids(indx);
    EXECUTE IMMEDIATE 'truncate table mds_hierarchy_all';
    insert into mds_hierarchy_all
    select * from l_mds_parents;
end;

t_mds_parents声明为

create or replace type r_mds_parents as object (
  id_mds number(5,0),
  id_employee number(5,0)
);
/

create or replace type t_mds_parents as table of r_mds_parents;
/

并且我得到一个异常ORA-00947:值不足

我真的需要在FORALL循环的每次迭代中将多行的结果集放入TABLE TYPE的变量中。我不能在BALLK COLLECT中使用l_mds_parents,因为它被限制在FORALL内。是否只有使用临时表而不是表变量的解决方案?

oracle collections bulk table-variable forall
1个回答
0
投票

我认为您无法使用forall完成此操作。您可以使用嵌套循环:

declare 
    TYPE t_mds_ids IS TABLE OF mds.id%TYPE;
    l_mds_ids t_mds_ids;
    l_mds_parents t_mds_parents;
begin
    SELECT id BULK COLLECT INTO l_mds_ids FROM mds;
    l_mds_parents := NEW t_mds_parents();
    FOR indx IN l_mds_ids.FIRST .. l_mds_ids.LAST LOOP
        FOR rec IN (
            select l_mds_ids(indx) as id_employee, ch.id_employee_parent
            FROM hierarchy_all ch
            CONNECT BY ch.id_employee = prior ch.id_employee_parent
            START WITH ch.id_employee = l_mds_ids(indx)
            ) LOOP
                l_mds_parents.extend();
                l_mds_parents(l_mds_parents.COUNT)
                    := NEW r_mds_parents (rec.id_employee, rec.id_employee_parent);
        END LOOP;
    END LOOP;
    EXECUTE IMMEDIATE 'truncate table mds_hierarchy_all';
    insert into mds_hierarchy_all
    select * from table(l_mds_parents);
end;
/

但是您根本不需要使用PL / SQL;使用单个层次查询,或更简单地说是递归子查询分解:

insert into mds_hierarchy_all /* (mds_id, id_employee) -- better to list columns */
with rcte (mds_id, id_employee) as (
  select m.id, ha.id_employee_parent
  from mds m
  join hierarchy_all ha on ha.id_employee = m.id
  union all
  select r.mds_id, ha.id_employee_parent
  from rcte r
  join hierarchy_all ha on ha.id_employee = r.id_employee
)
select * from rcte;
© www.soinside.com 2019 - 2024. All rights reserved.