如何在插入新内容之前对所有记录进行更新?

时间:2014-08-30 20:55:05

标签: sql postgresql plpgsql

我希望当我将新记录放到表中时,在插入之前我想将旧记录更新为ghost(有些像禁用),最后添加这个新记录。所以我准备了简单的触发函数

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行有什么问题???

1 个答案:

答案 0 :(得分: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