简体   繁体   中英

How to set date manually while importing from CSV file in PostgreSQL

I have a table tdummy2 , where I am importing the data from a csv file. Earlier I have set my create and update column as now() to auto update the column with current timestamp.

I now wanted to have my data imported with date now()-interval '7 days' and now-interval '30 days' etc.

This update needs to happen every different csv file import, meaning I have one csv data that should get update as now()-interval '7 days' and some csv file data as now()-interval -'14 days' and so on.

How can I do this using a PostgreSQL database? Should I have to do it manually every time or is there any way I can update the column at the same time the import is going on?

My current table schema:

create table tdummy2 (
 number1 integer,
 digit integer,
 type_digit integer,
 total integer,
 word character varying(256),
 apk character varying(256),
 version1 character varying(256),
 created  timestamp without time zone DEFAULT now() NOT NULL,
 updated  timestamp without time zone DEFAULT now() NOT NULL
);

You can set a custom column default for the duration of your transaction and reset it afterwards:

BEGIN;
ALTER TABLE tbl ALTER COLUMN created SET DEFAULT (now() - interval '7 days')
               ,ALTER COLUMN updated SET DEFAULT (now() - interval '7 days');

COPY ...;

ALTER TABLE tbl ALTER COLUMN created SET DEFAULT now()
               ,ALTER COLUMN updated SET DEFAULT now();
COMMIT;

Use a single ALTER TABLE statement for multiple columns, that's cheaper.

Be sure to do it all in a single transaction (inside a BEGIN; ... COMMIT; block) and concurrent transactions will never see the change. This will lock the table for the duration of the transaction, though.

That, or you use a staging table to COPY to and insert into the target table from there. Consider this related answer:
How to bulk insert only new rows in PostreSQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM