2014-08-30 65 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

相关问题