2013-02-16 306 views
1

有没有办法在表的定义中设置更新记录的时间,与插入记录时使用的缺省值设置为NOW()函数的方式相同?PostgreSQL有没有办法自动设置记录更新的时间?

+1

怎么样的后更新触发器? – Scotch 2013-02-16 08:08:16

+1

触发器是唯一选项 – 2013-02-16 08:16:38

+0

@a_horse_with_no_name您能向我展示一个例子吗? – vfclists 2013-02-16 08:51:41

回答

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) 
相关问题