简体   繁体   中英

psql import csv and generate uuid

I'm trying to import from CSV to Postgres and generate a uuid, uuid_generate_v4(), during the import to populate a table.

Postgres version: 14

Postgres Table

  • Country
    • id (primary key)
    • country_name
    • country_ISO_Code

Psql import

\copy "Country" (select uuid_generate_v4() as "id", "country_name", "country_ISO_code") FROM 'C:\Users\.......\data.csv' (format csv, header, delimiter ',')

However, that throws an error \copy: parse error at "as"

How do I properly instruct psql to use uuid_generate_v4() as id column?

You can't copy "from" a select statement. You need to define a default value for your primary key:

create table country
(
  id uuid primary key default gen_random_uuid(),
  country_name text not null,
  country_iso_code text not null
);

Then tell the \copy command that your input file only contains two columns:

\copy country (country_name, country_iso_code) from 'data.csv' (format csv, header, delimiter ',')

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