微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

database – 退出函数时删除临时表

我使用’on commit drop’选项在函数中使用临时表.我的问题是,在某些情况下,一个更全局的函数可以调用一个两次,所以“创建临时表”在提交之前被调用两次 – 所以我有正常的错误“relation [my_temp_table]已经存在”.

我使用函数末尾的临时表来返回“返回查询”中的行,所以在离开函数之前我无法手动删除表.

CREATE OR REPLACE FUNCTION my_function(_value text)
RETURNS setof my_table AS $$
DECLARE 
    resultCount integer := 0;
BEGIN

    create temp table my_temp_table on commit drop as
    select *
    from my_table 
    where value = _value ;

    select count(*) into resultCount from my_temp_table;
    if (resultCount = 0) then 
        raise exception 'value not found';
        end if;

    return query
    select * from my_temp_table;

END;$$LANGUAGE plpgsql VOLATILE COST 100;
ALTER FUNCTION my_function(text) OWNER TO postgres

如果你想知道为什么我直接使用临时表而不是my_table,那是因为我需要一个非常快的响应而且my_table非常大(几十万行)所以这样我只需要一次而不是三次(搜索,计数和返回).

我找到了一个不使用临时表并创建类型的解决方法,但是my_table的结构会改变很多次,实际上我有几十个“我的表”和关注的“我的函数”,所以这是一种不再写的方法每次我的表结构都会改变时,我的所有功能.

函数必须返回与其请求的表相同的结构.

离开功能时如何才能放弃桌面?或者有更好的解决方法吗?

解决方法

… return its rows in the “return query”,so I can’t manually drop the table before I leave the function.

其实你可以.在您的情况下,您可以使用多个RETURN QUERY.
手动后:

When a PL/pgsql function is declared to return SetoF […] the individual items to return are specified by a sequence of RETURN NEXT or RETURN QUERY commands,and then a final RETURN command with no argument is used to indicate that the function has finished executing

所以你可以这样做:

RETURN QUERY
       SELECT * FROM my_temp_table;
DROP TABLE my_temp_table;
RETURN;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐