防止PostgreSQL中的递归触发器

前端之家收集整理的这篇文章主要介绍了防止PostgreSQL中的递归触发器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何防止触发器的递归执行?假设我想在帐户图上构建一个“可树枝”的描述。所以我做的是当插入/更新新记录时,我更新了父记录的down_qty,这样就可以递归地触发更新触发器。

现在,我的代码是确定的 – 我把它放在UPDATE触发器的第一行:

-- prevents recursive trigger
if new.track_recursive_trigger <> old.track_recursive_trigger then
    return new;
end if;

这是我触发器的示例代码,当我需要更新父记录的数量时:

update account_category set 
    track_recursive_trigger = track_recursive_trigger + 1,-- i put this line to prevent recursive trigger
    down_qty = down_qty - (old.down_qty + 1)
where account_category_id = m_parent_account;

我在想,如果Postgresql有一种方法来检测递归触发器,而不会引入一个新的字段,类似于MSsql的trigger_nestlevel。

[编辑]

我循环在树中,我需要将每个account_category的down_qty反弹到其根。例如,我插入一个新的帐户类别,它需要增加其父帐户类别的down_qty,同样当我更改帐户类别的parent account_category时,我需要减少account_category之前的parent account_category的down_qty。虽然我觉得可以,但我并不是让Postgresql做递归触发器。在使用MSsql之前,触发器的递归深度级别仅限于16级。

在pg中,由你来跟踪触发器递归。 @H_502_19@

If a trigger function executes sql
commands then these commands might
fire triggers again. This is known as
cascading triggers. There is no direct
limitation on the number of cascade
levels. It is possible for cascades to
cause a recursive invocation of the
same trigger; for example,an INSERT
trigger might execute a command that
inserts an additional row into the
same table,causing the INSERT trigger
to be fired again. It is the trigger
programmer’s responsibility to avoid
infinite recursion in such scenarios.

http://www.postgresql.org/docs/8.3/static/trigger-definition.html

猜你在找的Postgre SQL相关文章