在 PostgreSQL 中更新行时更新时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1035980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update timestamp when row is updated in PostgreSQL
提问by bichonfrise74
In MySQL, we can execute this where it updates the column changetimestamp
every time the row is changed:
在 MySQL 中,我们可以在changetimestamp
每次更改行时更新列的地方执行此操作:
create table ab (
id int,
changetimestamp timestamp
NOT NULL
default CURRENT_TIMESTAMP
on update CURRENT_TIMESTAMP
);
Is there something similar to do the above in PostgreSQL?
在 PostgreSQL 中是否有类似的操作?
回答by Charles Ma
Create a function that updates the changetimestamp column of a table like so:
创建一个更新表的 changetimestamp 列的函数,如下所示:
CREATE OR REPLACE FUNCTION update_changetimestamp_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.changetimestamp = now();
RETURN NEW;
END;
$$ language 'plpgsql';
Create a trigger on the table that calls the update_changetimestamp_column() function whenever an update occurs like so:
在表上创建一个触发器,在更新发生时调用 update_changetimestamp_column() 函数,如下所示:
CREATE TRIGGER update_ab_changetimestamp BEFORE UPDATE
ON ab FOR EACH ROW EXECUTE PROCEDURE
update_changetimestamp_column();