【发布时间】:2021-10-14 17:20:20
【问题描述】:
我有多个 csv 文件,需要将它们复制到一个 postgres 数据库中。此外,我想为我的表添加一列,它可以显示每个文件的名称。有人可以帮忙吗?谢谢。
【问题讨论】:
标签: postgresql
我有多个 csv 文件,需要将它们复制到一个 postgres 数据库中。此外,我想为我的表添加一列,它可以显示每个文件的名称。有人可以帮忙吗?谢谢。
【问题讨论】:
标签: postgresql
您可以使用CSV 中的数据结构和另一个具有相同结构的临时表,并将列添加到CSV 文件的名称中,并制作plpgsql 代码以将文件加载到表格,例如:
文件:
file1.csv
hello,world21,2021
hello,world20,2020
hello,world12,2019
file2.csv
hello,world18,2018
hello,world17,2017
hello,world16,2016
加载 csv 文件的代码
create table csvtable (file text, hi text, world text, yr integer );
do $$
declare
files text[]:=array['file1.csv','file2.csv'];
copy_command text;
x text;
begin
create table csvtable_tmp ( hi text, world text, yr integer );
FOREACH x IN ARRAY files
LOOP
copy_command := 'copy csvtable_tmp from '''||x || '''csv delimiter '',''';
execute copy_command;
insert into csvtable select x,* from csvtable_tmp;
truncate csvtable_tmp;
END LOOP;
drop table csvtable_tmp;
end;
$$
db=# select * from csvtable;
file | hi | world | yr
-----------+-------+---------+------
file1.csv | hello | world21 | 2021
file1.csv | hello | world20 | 2020
file1.csv | hello | world12 | 2019
file2.csv | hello | world18 | 2018
file2.csv | hello | world17 | 2017
file2.csv | hello | world16 | 2016
(6 rows)
【讨论】: