2017-07-29 65 views
0

我正在寫一個函數,它將選擇並將得到的輸出合併到一個新表中 - 因此我試圖使用INTO函數。然而,我的獨立代碼工作,但一旦進入函數的地方,我得到一個錯誤,指出新的SELECT INTO表不是一個定義的變量(也許我失去了一些東西)。請看下面的代碼:PostgreSQL選擇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 

回答

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

雖然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