访问启动触发器的行

发布于 2024-10-31 22:59:27 字数 818 浏览 0 评论 0原文

我知道有一些方法可以在触发器定义中访问查询类型、表名称、oid 等:

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

无论如何,我是否有可能连续运行 UPDATE,从而启动触发器而无需实际上需要用唯一的 id 标记表中的每一行吗?

例如,如果我有用于存储日志的表,我在这里不需要任何唯一的ID...并且随着时间的推移,实际上可能会出现一些行,它们将是相等的。

CREATE TABLE users_log
(
  uid bigint NOT NULL,
  event smallint NOT NULL,
  source character varying,
  event_time timestamp with time zone
)

我知道,由于“带有时区的时间戳”数据类型的微秒精度,这种情况几乎不可能,但并非真的不可能......

那么我该如何在触发器中编写查询才能仅更新插入的行?

$BODY$BEGIN
    UPDATE "users_log" SET "event_time" = now(); -- this updates all rows

    -- WHERE "id" = NEW.id; - this is what i don't want

    RETURN NEW;
END;$BODY$

I know there're ways to access to query type, table names, oids etc. in trigger definitions:

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

Anyway, is there any chance that i run an UPDATE on a row, which started the trigger without actualy need to marking each row in the table by unique id?

e.g. if i have table for storing logs, i don't need any unique id here... and as the time goes there may actually appear some rows, which will be equal.

CREATE TABLE users_log
(
  uid bigint NOT NULL,
  event smallint NOT NULL,
  source character varying,
  event_time timestamp with time zone
)

I know, that due to microseconds precision in "timestamp with time zone" data type is this situation nearly impossible, but not really impossible...

So how shall i write the query in trigger to be able to UPDATE just the inserted row?

$BODY$BEGIN
    UPDATE "users_log" SET "event_time" = now(); -- this updates all rows

    -- WHERE "id" = NEW.id; - this is what i don't want

    RETURN NEW;
END;$BODY$

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩心不撩汉 2024-11-07 22:59:27

您只需在触发器中使用:

$BODY$BEGIN
    NEW.event_time = now();
    RETURN NEW;
END;$BODY$

它就可以正常工作 - 无需额外更新。不过,您需要将此触发器声明为 BEFORE TRIGGER。

You just use in your trigger:

$BODY$BEGIN
    NEW.event_time = now();
    RETURN NEW;
END;$BODY$

And it just works — no need for additional update. You need to declare this trigger as BEFORE TRIGGER though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文