2017-05-16 6 views
1

Cette commande fonctionne de PostgreSQL COPIE:Paramètres Pass pour fonction stockée dans Postgres

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

mais je veux que le tablename et filepath à Générée dynamiquement. Comment puis-je faire ceci?

J'ai essayé de suivre en appelant le 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; 

Je suis arrivé Erreur:

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)

Répondre

2

changement:

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

% Je cite objet db, alors que chemin est juste une chaîne

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.

souligné dans

+0

Got thanks.how à propos de tronquer la table juste avant la ligne d'exécuter le format –

+1

'exécuter le format ('tronquer% I', target_table);' –

+0

Thanks.I ont avez encore modifié la question –