PostgreSQL 中是否有临时表的替代方案来保存和操作结果集?

Nin*_*ina 6 postgresql temp-tables plpgsql

在 plpgsql 函数中,我需要保存 select 语句的结果集,并对该集执行许多后续查询操作。

我读到有关 PostgreSQL 中的临时表的信息,但这些表在会话/事务范围内可见,而我需要我的表(或任何保存结果集的数据结构)在本地可见并且仅存在于函数内,以便每个函数调用都可以有自己的副本(表/数据结构)

我只需要一个类似表的结构来保存函数调用中的选择结果集,而不是临时表。有这样的事吗?

kli*_*lin 2

并发会话可能有自己的(本地)同名临时表。下面是一个函数的示例,该函数不做任何明智的事情,只是创建一个临时表,返回其数据并在退出时删除该表:

create or replace function my_function()
returns table (id int, str text)
language plpgsql as $$
begin

    create temp table my_temp_table as
    select i as id, i::text as str
    from generate_series(1, 3) i;

    return query
    select *
    from my_temp_table;

    drop table my_temp_table;
end $$;
Run Code Online (Sandbox Code Playgroud)

该函数可以在并发会话中安全地运行。

drop table if exists...在函数的开头是一个合理的选择。不要忘记使用temptemporarycreate temp table...