postgresql 定时建表_我可以使用带标题的csv文件在PostgreSQL中自动创建表吗?

我在这里找到了第二种方法(来自mmatt)。 基本上,您在Postgres中调用一个函数(最后一个参数指定列数)。

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

这是mmatt的功能代码,由于我正在使用公共模式,因此必须对其进行一些修改。 (复制并粘贴到PgAdmin SQL编辑器中并运行它以创建函数)

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 VOLATILE

COST 100;

ALTER FUNCTION load_csv_file(text, text, integer)

OWNER TO postgres;

注意:导入与编码相关的文本文件是一个常见问题。 csv文件应采用UTF-8格式。 但是,有时通过尝试进行编码的程序并不能完全做到这一点。 我已通过在Notepad ++中打开文件并将其转换为ANSI并重新转换为UTF8的方式解决了此问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值