【问题标题】:Can timestamp take system time in the left over fields?时间戳可以在剩余字段中占用系统时间吗?
【发布时间】:2021-04-19 06:59:41
【问题描述】:

我有一个桌子假人。

create table dummy(id numeric,date timestamp);

因此,如果发送到时间戳列的数据格式为 2021-09-08。然后将数据插入为

2021-09-08 00:00:00

那么有没有办法,Postgres 可以将剩余字段(HH:MM:SS)作为当前系统时间以及日期?类似的东西

2021-09-08 11:34:00

由于我们不想将时间字段留空,这与日期数据类型几乎相同!

【问题讨论】:

  • 我希望你真的没有一个名为“日期”的列 - 这对于一个列来说太可怕了。
  • 不要使用timestamp作为数据类型,使用date。与其将两个不同的东西塞进一列,不如在当前时间使用 time 类型的单独列。那么你就不需要触发器了。
  • @a_horse_with_no_name。我同意。但只是以它为例。
  • 好的。但是已经有很多桌子在生产中。 @LaurenzAlbe

标签: postgresql timestamp


【解决方案1】:

你需要一个触发器:

首先触发函数来检查“零时间”,然后用当前时间调整它。

create or replace function adjust_time()
  returns trigger
as
$$
begin
  if new.date::time = time '00:00:00' then 
    new.date := new.date::date + localtime;
  end if;
  return new;
end;
$$
language plpgsql;

该函数检查给定的时间戳(混淆地命名为“日期”)是否在午夜有时间。如果是这种情况,它将用当前时间覆盖该时间。

那么你需要一个触发器:

create trigger adjust_time_trigger
before insert on dummy
for each row execute procedure adjust_time();

Online example

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 2013-02-22
    • 2011-01-06
    • 2013-05-31
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多