在PostgreSQL中更新行时更新时间戳 [英] Update timestamp when row is updated in PostgreSQL

查看:81
本文介绍了在PostgreSQL中更新行时更新时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MySQL中,我们可以在每次更改行时在其中更新列 changetimestamp 的地方执行此操作:

In MySQL, we can execute this where it updates the column changetimestamp every time the row is changed:

create table ab (
  id int, 
  changetimestamp timestamp 
    NOT NULL 
    default CURRENT_TIMESTAMP 
    on update CURRENT_TIMESTAMP 
);

在PostgreSQL中是否有类似上述操作?

Is there something similar to do the above in PostgreSQL?

推荐答案

创建一个更新表的changetimestamp列的函数,如下所示:

Create a function that updates the changetimestamp column of a table like so:

CREATE OR REPLACE FUNCTION update_changetimestamp_column()
RETURNS TRIGGER AS $$
BEGIN
   NEW.changetimestamp = now(); 
   RETURN NEW;
END;
$$ language 'plpgsql';

在表上创建一个触发器,只要发生如下更新,该触发器就会调用update_changetimestamp_column()函数: / p>

Create a trigger on the table that calls the update_changetimestamp_column() function whenever an update occurs like so:

    CREATE TRIGGER update_ab_changetimestamp BEFORE UPDATE
    ON ab FOR EACH ROW EXECUTE PROCEDURE 
    update_changetimestamp_column();

这篇关于在PostgreSQL中更新行时更新时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆