如何使用 postgres 11 从函数迭代中 return a table

How to return a table from iteration in function with postgres 11

创建了以下函数以在数据库 (PostgreSQL 11.4) 中进行管理。

为了完整起见,可以正常工作的功能:

CREATE OR REPLACE  FUNCTION entity_with_multiple_taskexec() 
    RETURNS TABLE(entitykey varchar) AS 
$func$
BEGIN
RETURN QUERY select distinct task.entitykey from
    (select  task.entitykey from task where dtype = 'PropagationTask' group by task.entitykey having count(*) > (select count(*) from conninstance)) more_than_one_entry
inner join task on task.entitykey = more_than_one_entry.entitykey 
inner join taskexec on taskexec.task_id = task.id order by task.entitykey asc;                   
END
$func$  LANGUAGE plpgsql;

但是第二个函数,我无法 return table,通过循环 entity_with_multiple_taskexec 函数的结果创建;

CREATE OR REPLACE  FUNCTION row_id_to_delete() 
    RETURNS TABLE(task_id varchar, taskexec_id varchar) AS 
$func$
DECLARE 
    entityrow RECORD;
    resultset RECORD;
BEGIN
        FOR entityrow IN SELECT entitykey FROM entity_with_multiple_taskexec() LOOP
            insert into resultset select task.id as task_id, taskexec.id as taskexec_id from task  
            inner join taskexec on taskexec.task_id = task.id where taskexec.entitykey = entityrow.entitykey order by taskexec.enddate desc offset 1 
        END LOOP;
    RETURN resultset;
END
$func$ LANGUAGE plpgsql;

这会因以下错误而中断

ERROR:  syntax error at or near "END"
LINE 12:   END LOOP;

我尝试过不同的方法。 return 和 table 有什么好的解决方案?

您不需要循环,只需加入函数就好像它是一个 table。

也没有必要使用PL/pgSQL,一个简单的language sql功能会更有效。

CREATE OR REPLACE  FUNCTION row_id_to_delete() 
    RETURNS TABLE(task_id varchar, taskexec_id varchar) AS 
$func$
  select task.id as task_id, taskexec.id as taskexec_id 
  from task  
    join taskexec on taskexec.task_id = task.id 
    join entity_with_multiple_taskexec() as mt on mt.entitykey = taskexec.entitykey
  order by taskexec.enddate desc 
  offset 1 
$func$ 
LANGUAGE sql;