How to import CSV file data into a PostgreSQL table?

前端 未结 19 2675
再見小時候
再見小時候 2020-11-22 02:14

How can I write a stored procedure that imports data from a CSV file and populates the table?

19条回答
  •  独厮守ぢ
    2020-11-22 03:19

    If you need simple mechanism to import from text/parse multiline CSV you could use:

    CREATE TABLE t   -- OR INSERT INTO tab(col_names)
    AS
    SELECT
       t.f[1] AS col1
      ,t.f[2]::int AS col2
      ,t.f[3]::date AS col3
      ,t.f[4] AS col4
    FROM (
      SELECT regexp_split_to_array(l, ',') AS f
      FROM regexp_split_to_table(
    $$a,1,2016-01-01,bbb
    c,2,2018-01-01,ffffd
    e,3,2019-01-01,eee$$, '\n') AS l) t;
    

    DBFiddle Demo

提交回复
热议问题