Default Value in a column when insert a new row

扶醉桌前 提交于 2021-01-28 11:00:34

问题


I have the table Photographies with the columns: Name, Author, Date, Updated date.

I would like to set Update date as default current_date when a new record is inserted or when a record is updated.

How should I proceed with this?


回答1:


Welcome to SO. Take a look at triggers.

Basically you only need to create a function to perform the updated ..

CREATE OR REPLACE FUNCTION update_date() RETURNS trigger AS
$BODY$
BEGIN
  NEW.updated = current_date;
  RETURN NEW;
END;
$BODY$ LANGUAGE 'plpgsql';

.. and attach it to a BEFORE INSERT OR UPDATE trigger like this

CREATE TRIGGER check_update
BEFORE INSERT OR UPDATE ON photographies
FOR EACH ROW EXECUTE PROCEDURE update_date();

After inserting a record ..

INSERT INTO photographies (name, author, date) 
VALUES ('José Saramago ','As Intermitências da Morte','2005-01-01');

.. you have your updated column with the current date

SELECT * FROM photographies ;
      name      |           author           |    date    |  updated   
----------------+----------------------------+------------+------------
 José Saramago  | As Intermitências da Morte | 2005-01-01 | 2019-12-06
(1 Zeile)


来源:https://stackoverflow.com/questions/59209278/default-value-in-a-column-when-insert-a-new-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!