转储个别文本字段成PSQL单独的文件

问题描述 投票:1回答:2

我有一个简单的表“编号,名称,内容”,我想所有的记录导出在一个名为“id_name.txt”与“内容”一栏(文本类型)内容的文件。这将创造尽可能多的文件是必要的。如何做到在psql里?

我想这样的事情,但分析不喜欢“arow.id”和“文件名”语法。

do $$
  declare
    arow record;
    filename varchar;
  begin
    for arow in
    select id, name, template from config_templates
    loop
      filename := '/tmp/' || arow.name || '.txt';
      COPY (select template from config_templates where id = arow.id) TO filename (FORMAT CSV); 
    end loop;
  end;
$$;
postgresql postgresql-9.3 psql postgresql-8.4
2个回答
1
投票

可能是你晚,但我发现你的问题的解决方案,所以想在这里分享我的解决方案。你的循环解决方案没有奏效,因为COPY命令等待文件名作为字符串常量。我的解决办法是使用动态查询与执行。请注意,以一倍EXECUTE PARAMS单引号。

do $$
  declare
    arow record;
    filename varchar;
  begin
    for arow in
    select id, name, template from config_templates 
    loop
      filename := '/tmp/' || arow.name::character varying(100) || '.txt';
      EXECUTE format('COPY (select template from config_templates where id = ''%s'' ) TO ''%s'' (FORMAT CSV)', arow.id::character varying(100), filename); 
    end loop;
  end;
$$;

1
投票

以psql的控制台,然后输入

\COPY table_name(column_name) TO 'path_of_text_file';
© www.soinside.com 2019 - 2024. All rights reserved.