gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:23:31 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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 $$;

该函数可以在并发 session 中安全运行。

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

中使用 temptemporary

关于postgresql - 是否有替代 PostgreSQL 中的临时表来保存和操作结果集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55928169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com