临时表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;

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

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...