如何将多个游标结果集插入一个 table

How to insert multiple cursor result set into one table

1 table 具有 table 结构-

 create table tab_abc
 ( id        varchar2(10),
   inv_bfr   varchar2(20),
   desc      varchar2(10),
   inv_afr   varchar2(10)  );

我这里定义了2个游标为C1 & C2 ->

 cursor C1 is select id, count(inv) AS "inv_bfr", desc from tab_a group by id, desc;

 cursor C2 is select count(inv) AS "inv_afr" from tab_a;

游标 C1C2 的结果集将插入 table tab_abc。游标 C1 将在执行一个 DML 操作之前打开,而游标 C2 将在 DML 操作执行之后打开。你能帮我吗我可以使用 OPEN CURSOR THEN FETCH 流程还是 FOR CURSOR LOOP INSERT INTO TABLE 流程。

您不需要在此处使用游标(或集合,更现实地说),甚至 PL/SQL。您可以在 'DML operaton perform' 步骤之前将数据插入 table ,然后在之后更新,例如合并:

-- initial population
insert into tab_abc (id, inv_bfr, descr, inv_afr)
select id, count(*) as inv_bfr, descr, 0 as inv_after
from tab_a
group by id, descr;

-- intermediate DML operation

-- post-DML update
merge into tab_abc t
using (
  select id, 0 as inv_bfr, descr, count(*) as inv_afr
  from tab_a
  group by id, descr
) afr
on (afr.id = t.id and afr.descr = t.descr)
when matched then
  update set inv_afr = afr.inv_afr
when not matched then
  insert (id, inv_bfr, descr, inv_afr)
  values (afr.id, afr.inv_bfr, afr.descr, afr.inv_afr);

当然,如果出于其他原因需要,您可以将所有内容包装在一个 PL/SQL 块中。

db<>fiddle demo 有一些虚构的行。