有没有办法导入一个csv文件到postgresql而不用从头创建新表?

ukdjmx9f  于 2023-03-08  发布在  PostgreSQL
关注(0)|答案(1)|浏览(183)

我有2个文件,并希望使用pgAdmin4将它们导入到PostgreSQL,所以我知道的唯一方法是创建表,手动创建列和从头开始的每一件事,但这将花费大量的时间,希望我没有错过任何东西,所以任何方法都可以简单地导入它们,PostgreSQL将标题视为列,我创建了表格,节省了大量的时间。我是新来的,所以我的问题形式可能是错误的,但这是我能问的最好的。

pbpqsu0x

pbpqsu0x1#

这是一个方法,我发现here(从mmatt)。基本上你调用一个函数在Postgres(最后参数指定列数)。

CREATE OR REPLACE FUNCTION load_csv_file(
target_table text,
csv_path text,
col_count integer)
RETURNS void AS
$BODY$

declare

iter integer; -- dummy integer to iterate columns with
col text; -- variable to keep the column name at each iteration
col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet

begin
set schema 'public';

create table temp_table ();

-- add just enough number of columns
for iter in 1..col_count
loop
    execute format('alter table temp_table add column col_%s text;', iter);
end loop;

-- copy the data from csv file
execute format('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_path);

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 format('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first)
loop
    execute format('alter table temp_table rename column col_%s to %s', iter, col);
    iter := iter + 1;
end loop;

-- delete the columns row
execute format('delete from temp_table where %s = %L', col_first, col_first);

-- change the temp table name to the name given as parameter, if not blank
if length(target_table) > 0 then
    execute format('alter table temp_table rename to %I', target_table);
    end if;

end;

$BODY$
  LANGUAGE plpgsql;

ALTER FUNCTION load_csv_file(text, text, integer)
  OWNER TO postgres;

使用此功能创建表后

select load_csv_file('myTable','C:/MyPath/MyFile.csv',24)

相关问题