2014-08-30 52 views
0

我希望當我把新的記錄表,在插入之前,我想更新舊記錄爲鬼(有些像禁用),並最終添加這個新的。所以,我準備簡單的觸發功能如何在插入新文件之前對所有記錄進行更新?

CREATE OR REPLACE FUNCTION trg_ghost_game_seed_ins_bef() 
    RETURNS trigger AS 
$$ 
BEGIN 
    UPDATE dice_game_seed SET ghost = true WHERE ghost = false; 
RETURN NEW; 
END 
$$ LANGUAGE plpgsql; 

CREATE TRIGGER ins_up_bef 
BEFORE INSERT OR UPDATE ON dice_game_seed 
FOR EACH ROW 
EXECUTE PROCEDURE trg_ghost_game_seed_ins_bef(); 

,當我試圖插入新記錄,我有信息

SQL statement "UPDATE dice_game_seed SET ghost = true WHERE ghost = false" 
PL/pgSQL function "trg_ghost_game_seed_ins_bef" line 3 at SQL statement 

但是,什麼是錯與3號線???

+0

你告訴到觸發:如果你使用任何類型的交易更新時更新,它就像一個無限循環 – Houari 2014-08-30 21:31:18

+0

是不是這種做法毫無意義。只是猜測。 – gorn 2014-08-30 22:16:53

回答

1

可以使用pg_trigger_depth()功能來解決無限遞歸:

create or replace function trg_ghost_game_seed_ins_bef() 
    returns trigger as 
$$ 
begin 
    if (pg_trigger_depth() = 1) then 
     update dice_game_seed set ghost = true where ghost = false; 
    end if; 
    return null; 
end 
$$ language plpgsql; 

create trigger ins_up_bef 
before insert or update on dice_game_seed 
for each statement 
execute procedure trg_ghost_game_seed_ins_bef(); 

您還可以使用,而不是一個行觸發器聲明觸發。

Example SQLFiddle

相關問題