有没有办法在表的定义中设置更新记录的时间,就像在插入记录时使用默认值设置为NOW()函数一样?
答案 0 :(得分:1)
这里你最好的选择是触发器。这是一个简单的选项,自包含:
CREATE TABLE triggertest (
id serial,
test text,
last_modified timestamp default now()
);
CREATE FUNCTION update_last_modified() RETURNS TRIGGER
LANGUAGE PLPGSQL AS
$$
BEGIN
NEW.last_modified := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER update_timestamp BEFORE UPDATE ON triggertest
FOR EACH ROW EXECUTE PROCEDURE update_last_modified();
insert into triggertest (test) values ('test');
select * from triggertest;
返回:
id | test | last_modified
----+------+----------------------------
1 | test | 2013-02-16 17:30:41.678707
(1 row)
我们的更新测试:
update triggertest set test = 'another';
select * from triggertest;
返回
id | test | last_modified
----+---------+--------------------------
1 | another | 2013-02-16 17:31:38.1126
(1 row)