我正在编写一个函数,它将选择结果并将输出加到一个新表中,因此我尝试使用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
发布于 2017-07-29 12:31:55
发布于 2017-07-29 12:35:18
尽管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
。
https://stackoverflow.com/questions/45393727
复制