获取存储过程 refcursor 输出并插入到临时 table

Fetch stored procedure refcursor output and insert into temp table

我有一个存储过程 (P1) returns 一个 refcursor 和其他一些文本数据类型值。 我有另一个程序 (P2),我需要在其中获取 P1 的 refcursor 输出并将其插入临时 table。临时 table 具有匹配的列和数据类型。

create or replace procedure P1(inout rfcur refcursor, in dtl text)
as
$$
begin
open rfcur for select * from tst_dump where ident = dtl;
end;
$$
language plpgsql;

create or replace P2(inout rfc refcursor, in dt_array text[])
as
$$
declare
i record;
cur refcursor;
begin
for i in array_lower(dt_array, 1)..array_upper(dt_array, 1) loop
call P1(cur, i);
--I need to fetch the result set from `cur` and store into a temp table `t_tab1`.
end loop;
end;
$$
language plpgsql;

是否可以在 Postgres 中实现这一点?

注意:我不应该对过程 P1 进行任何更改。

p2 可能看起来像这样:

CREATE PROCEDURE p2(IN dt_array text[])
   LANGUAGE plpgsql AS
$$DECLARE
   r record;
   i integer;
   cur refcursor;
BEGIN
   FOR i IN array_lower(dt_array, 1)..array_upper(dt_array, 1) LOOP
      CALL p1(cur, i::text);

      LOOP
         FETCH cur INTO r;
         EXIT WHEN NOT FOUND;
         INSERT INTO t_tab1 (...) VALUES (r.col1, r.col2, ...;
      END LOOP;
   END LOOP;
END;$$;

您应该缩进代码。这是你编程的基本要求。

在我看来,您做事的方式不对。使用过程和游标会使一切变得复杂并使其变慢。

你应该这样做

INSERT INTO t_tab
SELECT /* your original query */;