加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

防止PostgreSQL中的递归触发器

发布时间:2020-12-13 16:35:44 所属栏目:百科 来源:网络整理
导读:如何防止触发器的递归执行?假设我想在帐户图上构建一个“可树枝”的描述。所以我做的是当插入/更新新记录时,我更新了父记录的down_qty,这样就可以递归地触发更新触发器。 现在,我的代码是确定的 – 我把它放在UPDATE触发器的第一行: -- prevents recurs
如何防止触发器的递归执行?假设我想在帐户图上构建一个“可树枝”的描述。所以我做的是当插入/更新新记录时,我更新了父记录的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中,由你来跟踪触发器递归。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读