extract date from timestamp in postgreSQL

时间:2015-06-26 10:14:30

标签: postgresql

we have a table of data that looks like:

|id|date1     |timestamp1         |
-----------------------------
|1 |2015-06-23|2015-06-23 16:02:00|
-----------------------------
|2 |2015-01-02|2015-01-02 11:32:00|

I tried to create a function and trigger which is not working, looks like this:

CREATE OR REPLACE FUNCTION insert_date1_trg_func()
RETURNS trigger AS
$BODY$
begin
update schema.table set
date1 = extract(date from new.timestamp1)
where id = new.id;
return null;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

trigger

CREATE TRIGGER insert_date1_trg_func()
AFTER INSERT or update
ON schema.table
FOR EACH ROW
EXECUTE PROCEDURE insert_date1_trg_func();

I am getting an error type date but expression double precision.

1 个答案:

答案 0 :(得分:1)

If you want to set "date1" in the update trigger, it should be like this:

CREATE OR REPLACE FUNCTION insert_date1_trg_func() RETURNS trigger AS $BODY$
BEGIN
  NEW.date1 = date_trunc('day', NEW.timestamp1)::date;
  RETURN NEW;
END; $BODY$ LANGUAGE plpgsql STABLE;

Trigger:

CREATE TRIGGER insert_date1_trg_func()
BEFORE INSERT OR UPDATE ON schema.table
FOR EACH ROW EXECUTE PROCEDURE insert_date1_trg_func();

Note that the trigger should fire BEFORE the insert or update or the changes will not persist in the database.