首页 > 解决方案 > Postgres 将列值更新为 time.Now()

问题描述

当列更新到paid_attime.Now()orders,我需要将列更新到表上是否可以在 postgres 上创建触发器?他们都在同一张桌子上statuspaidorders

标签: postgresql

解决方案


是否可以在 postgres 上创建触发器

是的,这是可能的。

如手册中所述,您首先需要一个触发功能

create function update_paid_at()
  returns trigger
as
$$
begin
  new.paid_at := now();
  return new;
end;
$$
language plpglsql;

然后你需要一个触发器定义

create trigger update_orders_trigger
   before update on orders
   for each row
   when (new.status = 'paid' and new.status <> old.status)
   execute procedure update_paid_at();

触发器仅在状态更改'paid'然后设置paid_at列的值时触发。


推荐阅读