【问题标题】:PostgreSQL select INTO functionPostgreSQL 选择 INTO 函数
【发布时间】:2018-01-05 17:13:36
【问题描述】:

我正在编写一个函数,它将选择并将结果输出求和到一个新表中 - 因此我尝试使用 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

【问题讨论】:

    标签: postgresql postgis create-table insert-into


    【解决方案1】:

    the documentation:

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

    使用CREATE TABLE AS

    【讨论】:

      【解决方案2】:

      虽然SELECT ... INTO new_table 是有效的 PostgreSQL,但它的使用已被弃用(或者,至少,“不推荐”)。它在 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-23
        • 2022-01-05
        • 2012-06-01
        • 1970-01-01
        • 2011-10-02
        • 2019-01-10
        • 2014-04-09
        • 1970-01-01
        相关资源
        最近更新 更多