是否有替代 PostgreSQL 中的临时表来保存和操作结果集?
Is there an alternative to temp tables in PostgreSQL to hold and manipulate result sets?
在 plpgsql 函数中,我需要保存 select 语句的结果集并执行许多后续的 查询 和 操作 在那个集合上。
我在 PostgreSQL 中读到过临时 tables,但是这些 tables 在 session/transaction 范围内可见,而我需要我的 table(或任何数据结构)保持结果集)在本地可见并且只存在于函数中,这样每个函数调用都可以有自己的副本(table/data 结构)
我只需要一个 table 类似的结构来在函数调用中保存 select 结果集,而不是临时 tables。
有这种东西吗?
并发会话可能有自己的(本地)同名临时 table。这是一个函数的例子,它没有做任何明智的事情,而是创建一个临时 table,returns 其数据并在退出时删除 table:
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 $$;
函数可以在并发会话中安全地 运行。
函数开头的 drop table if exists...
是一个合理的替代方案。不要忘记在 create temp table...
中使用 temp
或 temporary
在 plpgsql 函数中,我需要保存 select 语句的结果集并执行许多后续的 查询 和 操作 在那个集合上。
我在 PostgreSQL 中读到过临时 tables,但是这些 tables 在 session/transaction 范围内可见,而我需要我的 table(或任何数据结构)保持结果集)在本地可见并且只存在于函数中,这样每个函数调用都可以有自己的副本(table/data 结构)
我只需要一个 table 类似的结构来在函数调用中保存 select 结果集,而不是临时 tables。 有这种东西吗?
并发会话可能有自己的(本地)同名临时 table。这是一个函数的例子,它没有做任何明智的事情,而是创建一个临时 table,returns 其数据并在退出时删除 table:
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 $$;
函数可以在并发会话中安全地 运行。
函数开头的drop table if exists...
是一个合理的替代方案。不要忘记在 create temp table...
temp
或 temporary