PostgreSQL选择INTO功能

时间:2017-07-29 20:25:35

标签: postgresql postgis create-table insert-into

我正在编写一个函数,它会将结果输出选择并汇总到一个新表中 - 因此我尝试使用INTO函数。但是,我的独立代码工作,但一旦进入函数的位置,我得到一个错误,指出新的SELECT INTO表不是一个已定义的变量(也许我错过了一些东西)。请参阅以下代码:

CREATE OR REPLACE FUNCTION rev_1.calculate_costing_layer()
  RETURNS trigger AS
$BODY$
BEGIN
   -- This will create an intersection between pipelines and sum the cost to a new table for output
   -- May need to create individual cost columns- Will also keep infrastructure costing seperated
   --DROP table rev_1.costing_layer;
   SELECT inyaninga_phases.geom, catchment_e_gravity_lines.name, SUM(catchment_e_gravity_lines.cost) AS gravity_sum
   INTO rev_1.costing_layer
   FROM rev_1.inyaninga_phases 
   ON ST_Intersects(catchment_e_gravity_lines.geom,inyaninga_phases.geom)
   GROUP BY catchment_e_gravity_lines.name, inyaninga_phases.geom;
  RETURN NEW;
END;
$BODY$
language plpgsql

2 个答案:

答案 0 :(得分:4)

the documentation

  

CREATE TABLE AS在功能上类似于SELECT INTO。 CREATE TABLE AS是推荐的语法,因为这种形式的SELECT INTO在ECPG或PL / pgSQL中不可用,因为它们以不同的方式解释INTO子句。此外,CREATE TABLE AS提供了SELECT INTO提供的功能的超集。

使用CREATE TABLE AS

答案 1 :(得分:1)

虽然SELECT ... INTO new_table是有效的PostgreSQL,但它的使用已被弃用(或至少,#34;未推荐")。它在PL / PGSQL中根本不起作用,因为INSERT INTO用于将结果输入变量

如果您想创建一个新表,您应该使用:

CREATE TABLE rev_1.costing_layer AS
SELECT 
    inyaninga_phases.geom, catchment_e_gravity_lines.name, SUM(catchment_e_gravity_lines.cost) AS gravity_sum
FROM 
    rev_1.inyaninga_phases 
    ON ST_Intersects(catchment_e_gravity_lines.geom,inyaninga_phases.geom)
GROUP BY 
    catchment_e_gravity_lines.name, inyaninga_phases.geom;

如果表已经创建了,你只想在其中插入一个新行,你应该使用:

INSERT INTO
     rev_1.costing_layer
     (geom, name, gravity_sum)
-- Same select than before
SELECT 
    inyaninga_phases.geom, catchment_e_gravity_lines.name, SUM(catchment_e_gravity_lines.cost) AS gravity_sum
FROM 
    rev_1.inyaninga_phases 
    ON ST_Intersects(catchment_e_gravity_lines.geom,inyaninga_phases.geom)
GROUP BY 
    catchment_e_gravity_lines.name, inyaninga_phases.geom;

在触发功能中,您每次都不太可能创建新表格,因此,我猜您想要INSERT而不是CREATE TABLE ... AS。< / p>

相关问题