【问题标题】:How to make update on all records before insert new?如何在插入新记录之前更新所有记录?
【发布时间】:2014-08-30 20:55:05
【问题描述】:

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

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

【问题讨论】:

  • 你在告诉触发器:更新时更新,就像一个死循环
  • 如果您使用任何类型的事务,这种方法是否毫无意义。只是猜测。

标签: sql postgresql plpgsql


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-08-14
    • 1970-01-01
    • 2021-12-21
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2019-06-23
    • 2012-05-11
    相关资源
    最近更新 更多