COPY with dynamic file name

后端 未结 1 1858
小鲜肉
小鲜肉 2020-11-30 15:04

I am trying to write a function to load csv data into a table. I want the input argument to be the path to the file.

CREATE OR REPLACE FUNCTION public.loadd         


        
相关标签:
1条回答
  • 2020-11-30 15:52

    You need dynamic SQL:

    CREATE OR REPLACE FUNCTION loaddata(filepathname text)
      RETURNS void AS
    $func$
    BEGIN
       EXECUTE format ('
       COPY climatedata(
             climatestationid
           , date
             ... -- more columns 
           , tminsflag)
       FROM %L (FORMAT CSV, HEADER)'  -- current syntax
               -- WITH CSV HEADER'    -- tolerated legacy syntax
       , $1);  -- pass function parameter filepathname to format() 
    END
    $func$ LANGUAGE plpgsql;
    

    format() requires PostgreSQL 9.1+.
    Pass the file name without extra set of (escaped) single quotes:

    SELECT loaddata('/absolute/path/to/my/file.csv')
    

    format() with %L escapes the file name safely. Would be susceptible to SQL injection without it.


    Aside, you have a function name mismatch:

    CREATE OR REPLACE FUNCTION public.loaddata(filepathname varchar)
    ...
    ALTER FUNCTION public.filltmaxa(character varying)

    0 讨论(0)
提交回复
热议问题