1

This PostgreSQL COPY command works:

copy a from '/tmp/main.csv' WITH (FORMAT csv)

but I want the tablename and filepath to be dynamically generated. How can I do this?

I did try with following by calling the select import_csv('/tmp/main.csv','a');

CREATE OR REPLACE FUNCTION import_csv(
    csv_path text,
    target_table text)
  RETURNS void AS
$BODY$
begin
    set schema 'public';
    raise notice 'CSV PATH: %,TABLE NAME: %',csv_path,target_table;
    execute format('copy %I from %I WITH (FORMAT csv)',target_table, csv_path);
    return;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION import_csv(text, text)
  OWNER TO postgres;

I got Error:

NOTICE: CSV PATH: /tmp/main.csv,TABLE NAME: a

ERROR: syntax error at or near ""/tmp/main.csv""

LINE 1: copy a from "/tmp/main.csv" WITH (FORMAT csv)

1 Answer 1

3

change to:

execute format('copy %I from %L WITH (FORMAT csv)',target_table, csv_path);

%I quotes db object, while path is just a string

https://www.postgresql.org/docs/current/static/functions-string.html:

The type of format conversion to use to produce the format specifier's output. The following types are supported:

s formats the argument value as a simple string. A null value is treated as an empty string.

I treats the argument value as an SQL identifier, double-quoting it if necessary. It is an error for the value to be null (equivalent to quote_ident).

L quotes the argument value as an SQL literal. A null value is displayed as the string NULL, without quotes (equivalent to quote_nullable).

In addition to the format specifiers described above, the special sequence %% may be used to output a literal % character.

emphasis mine

Sign up to request clarification or add additional context in comments.

2 Comments

Got thanks.how about for truncate the table just before the line execute format
@AjayTakur If I answered your question, could you please accept it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.