【问题标题】:Copy few of the columns of a csv file into a table error将 csv 文件的几列复制到表错误中
【发布时间】:2017-02-11 11:34:27
【问题描述】:

我在以 District.csv 命名的 Excel 表中有数据,只需将少数列从 excel 导入以 hc_court_master 命名的 postgres 表

copy hc_court_master (district_cd, category,category1,shrt_nm,court_name)
from 'D:\district.csv'
with (format csv)

我遇到了错误

ERROR: extra data after last expected column
SQL state: 22P04
Context: COPY hc_court_master, line 1: "court_code,court_name,short_c_name,category,dist_no,dist_name,category1"

【问题讨论】:

    标签: excel postgresql csv copy etl


    【解决方案1】:

    有两个问题:

    1. 您不能只从 csv 复制几列。而且你不能改变他们的顺序。

    2. 只需在 with 子句中使用 HEADER 关键字即可忽略 csv 文件中的标题。

     copy hc_court_master (court_code, court_name, short_c_name,
           category, dist_no, dist_name, category1)
     from 'D:\district.csv'
     with (format csv, HEADER)
    

    如果您不希望表中的所有字段,您可以:

    1. 导入后更改表删除列

    2. 导入临时表,然后运行 ​​INSERT INTO ... SELECT ...

    【讨论】:

      【解决方案2】:

      正如这里提到的,您不能从 CSV 加载选定的字段,只能加载整个数据。所以

      begin; -- Start transaction
      
      do $$
      begin
        create temp table t( -- Create table to load data from CSV
          court_code text, -- There are whole list of columns ...
          court_name text,
          short_c_name text,
          category text,
          dist_no text,
          dist_name text,
          category1 text)  on commit drop;
        copy t from '/home/temp/a.csv' with (
          format CSV,
          header -- To ignore first line
          );
      end $$;
      
      insert into hc_court_master (district_cd, category,category1,shrt_nm,court_name)
      select <appropriate columns> from t;
      commit;
      

      【讨论】:

        【解决方案3】:
        copy hc_court_master (district_cd, category,category1,shrt_nm,court_name)
        from 'D:\district.csv'
        with (format csv)
        

        我认为只有当您的 csv 仅包含必需的列(district_cd、category、category1、shrt_nm、court_name)时,上面的 sql 才会起作用。

        您可以删除多余的列然后尝试上传。

        请参考以下链接

        Copy a few of the columns of a csv file into a table

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-19
          • 2017-08-13
          • 2014-12-08
          • 2013-01-14
          • 1970-01-01
          • 2012-07-15
          • 2020-07-05
          • 1970-01-01
          相关资源
          最近更新 更多