我已经复制了函数(来自其中一个webportal并相应地修改)以将数据从csv文件复制到表。
create or replace function public.load_csv_file
(
target_table text,
csv_path text,
col_count integer
)
returns void as $$
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 insert_from_csv ();
-- add just enough number of columns
for iter in 1..col_count
loop
execute format('alter table insert_from_csv add column col_%s text;', iter);
end loop;
-- copy the data from csv file
execute format('copy insert_from_csv from %L with delimiter '','' quote ''"'' csv ', csv_path);
iter := 1;
col_first := (select col_1 from insert_from_csv 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 insert_from_csv rename column col_%s to %s', iter, col);
iter := iter + 1;
end loop;
-- delete the columns row
execute format('delete from insert_from_csv 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 insert_from_csv rename to %I', target_table);
end if;
end;
$$ language plpgsql;
和 传递参数为
选择load_csv_file('客户' C:\ Insert_postgres.csv',4)
但收到错误消息
错误:无法打开文件" C:\ Insert_postgres.csv"阅读:没有这样的文件或目录 背景:SQL语句"从E&C; \ C:\ Insert_postgres.csv'复制insert_from_csv与分隔符','引用'"' csv" PL / pgSQL函数load_csv_file(text,text,integer)在EXECUTE
的第21行任何帮助表示感谢。
答案 0 :(得分:1)
我尝试将文件移到其他位置,' C:\ testData \ Insert_postgres.csv'
最初我在下面尝试
选择load_csv_file('客户' C:\ Insert_postgres.csv',4)
并收到错误
经过多次尝试后,我想我会在c盘上创建一个文件夹,并将csv文件放在该文件夹中,然后就可以了。
选择load_csv_file('客户' C:\ testData \ Insert_postgres.csv',4)。
似乎postgres无法直接从c盘访问文件,但如果文件放在c:驱动器上的文件夹中,则成功运行。