在存储过程中使用SELECT INTO [tableName]不起作用

时间:2010-11-24 19:12:25

标签: postgresql

我正在尝试在

中使用表名
SELECT INTO [tableName]

但它抱怨[tableName]应该是记录变量,行变量或标量变量列表。如何将select的结果放入表而不是存储过程中的变量?

3 个答案:

答案 0 :(得分:6)

如手册中所述:

http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW

您不能在pl / pgSQL过程中使用该语法。

您需要使用以下语法:

CREATE TABLE new_table
AS
SELECT ....

答案 1 :(得分:1)

你想要一个INSERT INTO ... SELECT查询,而不是SELECT INTO。例如:

INSERT INTO my_table (name, my_avg) SELECT name, AVG(col) FROM your_table GROUP BY name

除非你真的想创建一个新的表,SELECT INTO应该正常工作:

vsavard_db=> SELECT 1 INTO b;
SELECT
Time : 47,268 ms
vsavard_db=> SELECT * FROM b;
 ?column? 
----------
        1
(1 line)

答案 2 :(得分:0)

您的语法错误,根据http://www.postgresql.org/docs/8.1/static/sql-selectinto.html您的存储过程应遵循以下模式:

SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ AS output_name ] [, ...]
INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
[ LIMIT { count | ALL } ]
[ OFFSET start ]
[ FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ] ]

EX:SELECT * INTO my_table WHERE x = @myParam