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

临时表postgresql函数

我无法找到创建(和使用)表的语法的明确解释,仅用于函数的内部计算.请问有人给我一个语法例吗?

从我发现的,我尝试了这个(在temp_table之前有和没有@):

CREATE FUNCTION test.myfunction()
RETURNS SetoF test.out_table
AS $$

DECLARE @temp_table TABLE
( 
        id int,value text
 )
BEGIN
 INSERT INTO @temp_table 
        SELECT id,value
        FROM test.another_table;

 INSERT INTO test.out_table
        SELECT id,value
        FROM @temp_table;
RETURN END
$$LANGUAGE sql;

我明白了:

ERROR: Syntax error at or near “DECLARE”
LINE 5: DECLARE @temp_table TABLE

我也试过建议here的CREATE TABLE方法,这样:

CREATE FUNCTION test.myfunction()
RETURNS SetoF test.out_table
AS $$

    CREATE TABLE temp_table AS
        SELECT id,value
        FROM test.another_table;

    INSERT INTO test.out_table
        SELECT id,value
        FROM temp_table;

$$LANGUAGE sql;

我得到了这个:

ERROR: relation “temp_table ” does not exist
LINE 11: FROM temp_table

(显然,我知道temp_table对于我在上面的代码中所做的事情不是必需的,但那不是重点:) =>我想了解让它工作的语法)

创建临时表的适当语法是
create temp table...

但是你必须确保在现有函数出现之前删除临时表.另外,我建议使用这种语法:

CREATE TEMP TABLE IF NOT EXISTS temp_table AS
    SELECT id,value
    FROM test.another_table;

因此你的功能将是这样的:

CREATE FUNCTION test.myfunction()
RETURNS SetoF test.out_table
AS $$

    CREATE TEMP TABLE IF NOT EXISTS temp_table AS
        SELECT id,value
        FROM temp_table;

DROP TABLE temp_table;

$$LANGUAGE sql;

但如果我能这么善良,我想重写这个功能,这样更正确:

CREATE FUNCTION test.myfunction()
RETURNS TABLE (id int,value varchar) -- change your datatype as needed
AS $$
BEGIN;
CREATE TEMP TABLE IF NOT EXISTS temp_table AS
    SELECT id,value
    FROM test.another_table;

INSERT INTO test.out_table
    SELECT id,value
    FROM temp_table;

DROP TABLE temp_table;

RETURN QUERY 
SELECT id,value
from temp_table;

END;
$$LANGUAGE plpgsql;

未测试;如果失败,请告诉我.

原文地址:https://www.jb51.cc/postgresql/191636.html

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

相关推荐