要自动填写的日期字段

时间:2013-09-23 13:56:08

标签: sql database postgresql

我正在使用PostgreSQL并创建了下表:

CREATE TABLE "TrainingMatrix"
(
  payroll text NOT NULL,
  "TrainingName" text NOT NULL,
  "Institute" text,
  "TrainingDate" date NOT NULL,
  "ExpiryDate" date,
  "RecorderName" text,
  "EnteringDate" date,
  CONSTRAINT "TrainingMatrix_pkey" PRIMARY KEY (payroll, "TrainingName", "TrainingDate")
)

我想让EnteringDate由每台输入记录的机器中的当前日期自动填充。

4 个答案:

答案 0 :(得分:1)

CREATE TABLE "TrainingMatrix"
(
  payroll text NOT NULL,
  "TrainingName" text NOT NULL,
  "Institute" text,
  "TrainingDate" date NOT NULL,
  "ExpiryDate" date,
  "RecorderName" text,
  "EnteringDate" date not null default current_timestamp,
  CONSTRAINT "TrainingMatrix_pkey" PRIMARY KEY (payroll, "TrainingName", "TrainingDate")
)

current_timestamp等于Now()将给出当前日期&时间(包括时区)http://www.postgresql.org/docs/8.1/static/functions-datetime.html

将列定义为非null也有助于确保没有明确输入没有时间戳的记录。

答案 1 :(得分:1)

CREATE TABLE "TrainingMatrix"
(
  payroll text NOT NULL,
  "TrainingName" text NOT NULL,
  "Institute" text,
  "TrainingDate" date NOT NULL,
  "ExpiryDate" date,
  "RecorderName" text,
  "EnteringDate" date NOT NULL default current_date,--"EnteringDate" date,
  CONSTRAINT "TrainingMatrix_pkey" PRIMARY KEY (payroll, "TrainingName", "TrainingDate")
)

答案 2 :(得分:0)

使用默认关键字

column datatype default sysdate

同时检查

How to set default value for column of new created table from select statement in 11g

答案 3 :(得分:0)

通过使用默认的sysdate,您可以获得所需的输出。

CREATE TABLE "TrainingMatrix"
(
  payroll text NOT NULL,
  "TrainingName" text NOT NULL,
  "Institute" text,
  "TrainingDate" date NOT NULL,
  "ExpiryDate" date,
  "RecorderName" text,
  "EnteringDate" date default sysdate,
  CONSTRAINT "TrainingMatrix_pkey" PRIMARY KEY (payroll, "TrainingName", "TrainingDate")
)
相关问题