postgresql - 如何使用 postgres 11 从函数迭代返回表

标签 postgresql plpgsql postgresql-11

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

  • entity_with_multiple_taskexec:返回应该进行管理的实体列表。
  • row_id_to_delete:返回要删除的 id 的元组

为了完整起见,功能正常:

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;

但是第二个函数,我无法返回一个表,该表是通过循环遍历 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;

我尝试过不同的方法。返回表的好的解决方案是什么?

最佳答案

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

也不需要为此使用PL/pgSQL,一个简单的语言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;

关于postgresql - 如何使用 postgres 11 从函数迭代返回表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371465/

相关文章:

postgresql - 如何从 PostgreSQL 存储过程返回结果集?

bash - 从 postgres 函数/过程/触发器执行 Bash 脚本(Shell 脚本)

r - RPostgreSQL 中的查询非常慢

Python psycopg2 postgres 选择包含字段名称的列

postgresql - 如何将带有空值的csv文件导入Postgres?

postgresql - 执行动态交叉表查询

postgresql - 未初始化 PL/pgSQL 常量 : is it possible?

postgresql - 无法从客户端连接到 PostgreSQL - 错误超时

postgresql - 在postgres中使用变量中的方法名称调用存储过程

selinux - PostgreSQL 11 配置不允许 pgAdmin4 连接