如何使用现在()和\Copy from 命令更新我的 Postgres 数据库中名为 created_on 的列的当前



我正在使用copycsv文件从本地psql加载到远程服务器中的postgres数据库中。问题是有一个名为created_on的列,每当记录更新时,它都需要更新到系统时间,但created_on具有没有时区类型的时间戳,并且不为空约束。那么如何加载csv文件,同时在一个语句中将created_on设置为现在呢?

copy counter_template(counter_name,category,counter_type_name,module_name,default_instance_name,query_string,execution_type,user_id,enterprise_id,created_by,display_name,unit) from 'F:Worktest2.csv' with delimiter as ',' FORCE NOT NULL default_instance_name,query_string,execution_type HEADER csv;

错误:

ERROR:  null value in column "created_on" violates not-null constraint
DETAIL:  Failing row contains (5470, hostname, status, null, Apache_Metricset, null, Application, f, f, null, f, f, 1, , f, , , f, 1, 0, f, null, null, 1, null, Hostname, keyword, f, f, f, 0, , f, null, f, null).

你需要一个BEFORE INSERT触发器 在提供created_on当前时间的表上。

那么如何加载 csv 文件并同时设置 created_on到现在在一个声明中?

列上带有DEFAULT子句。

ALTER TABLE counter_template ALTER COLUMN created_on SET DEFAULT now();

之后,每次插入新行并且没有为此列指定值时,无论是COPY还是INSERT,该值都将基于此DEFAULT表达式填充。

最新更新