将数据从csv文件导入到postgres表中,而无需先创建表

穆罕默德

我有数十个csv文件,每个文件中都有一百多列。我需要将这些文件上传到postgres表中,以便对其进行处理并将数据传输到关系表中。我不想手动处理每个文件以提取列名,因为这可能是重复的过程。pgAdmin导入工具和COPY函数都不会处理第一行以创建表的列。那么,解决此问题的最佳方法是什么?

穆罕默德

我不知道这是否是一种合理的方法(由于大量使用动态sql和用于提取列名的方法),这对我有用:

create or replace function data.csv_to_table (in target_table text, in csv_path text, in col_count integer)

returns void as $$

declare 

iter integer; --dummy integer to iterate with
col text; --dummy variable to iterate with
col_first text; --first column label, e.g., top left corner on a csv file or spreadsheet

begin
    set schema 'data';

    drop table if exists temp_table;

    create table temp_table ();

    -- add just enough number of columns
    for iter in 1..col_count
    loop
        execute 'alter table temp_table add column col_' || iter || ' varchar;';
    end loop;

    -- copy the data from csv file
    execute 'copy temp_table from ''' || csv_path || ''' with delimiter '',''';

    iter := 1;
    col_first := (select col_1 from temp_table limit 1);

    -- update the column names based on the first row which has the column names
    for col in execute 'select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = ''' || col_first || ''''
    loop
        execute 'alter table temp_table rename column col_' || iter || ' to ' || col;
        iter := iter + 1;
    end loop;

    -- delete the columns row
    execute 'delete from temp_table where ' || col_first || ' = ''' || col_first || '''';

    -- change the temp table name to the parameter given if not blank
    if length(target_table) > 0 then
        execute 'drop table if exists ' || target_table;
        execute 'alter table temp_table rename to ' || target_table;
    end if;

end;

$$ language plpgsql;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我应该如何使用pgAdmin 3将数据从CSV导入到Postgres表中?

如何通过Java代码将CSV文件数据导入到PostgreSQL表中?

将多个分隔的文本文件导入到SQL Server数据库中并自动创建表

将数据从.avro文件导入到配置单元表

C#将.CSV数据导入到MySQL表中仅复制1列

如何将csv文件导入到mysql表中并自动递增

KDB-似乎无法将csv文件导入到表中

将.less文件导入到单个.less中,而无需重新编译

从CSV数据导入到Postgresql中,无需复制

如何将excel表中的数据同时导入到关系表中

表中的日期为dd.mm.yyyy-无法通过csv导入到postgres

将数据导入到其中具有嵌套表的新表中

以编程方式将CA Trust证书导入到现有密钥库文件中,而无需使用keytool

读取csv并导入到数据表(Python)

python gspread将csv导入到特定工作表

使用导入导出向导将DAT文件内容导入到SQL Server表中-错误

使用Google Script将多个CSV文件导入到Google工作表

不使用主键将CSV文件导入到Mysql表

将数据表从网页导入到 Google Sheets

从Windows中的.csv文件将数据导入到mongodb数据库中

需要将csv文件合并为一个文件,然后将csv文件导入到mysql中的表中

使用sql将数据从文件csv导入到Oracle

将数据从CSV文件导入到InfluxDB

将数据从 csv 文件导入到 R

将数据库中的日期导入到Excel工作表中

如何解析文件名,并使用shellscript将数据导入到csv文件中?

将Excel Listobject导入到Access表中

postgres:将csv文件导入表

将Excel数据导入到现有的SQL Server 2005表中