创建了以下函数以在数据库 (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/