问题
I am trying to create this statement into a function:
\copy aux("nombre") TO '/home/david/lugares.csv' delimiters ';';
So I do the next:
CREATE OR REPLACE FUNCTION crearcsv()
RETURNS void AS
$BODY$
DECLARE STATEMENT TEXT;
BEGIN
RAISE NOTICE 'CREAR CSV';
STATEMENT:= '\copy aux ("nombre") TO ''/home/david/lugares.csv'' delimiters '';'';';
RAISE NOTICE '%',STATEMENT;
EXECUTE STATEMENT;
END;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
But I get the next when I call to the function:
NOTICE: \copy aux ("nombre") TO '/home/david/lugares.csv' delimiters ';'; ERROR: syntax error at or near "\"
LINE 1: \copy aux ("nombre") TO '/home/david/lugares.csv' delimiters... ^
QUERY: \copy aux ("nombre") TO '/home/david/lugares.csv' delimiters ';';
CONTEXT: PL/pgSQL function crearcsv() line 7 at EXECUTE statement**
This statement works fine in PSQL console
Any help?
回答1:
You can simply change \copy
in copy
. COPY
is the "sql variant" of \copy
, works in a database function, the syntax is identical but has some differences which can be relevant for you:
COPY is the Postgres method of data-loading. Postgres's COPY comes in two separate variants, COPY and \COPY: COPY is server based, \COPY is client based.
COPY will be run by the PostgreSQL backend (user "postgres"). The backend user requires permissions to read & write to the data file in order to copy from/to it. You need to use an absolute pathname with COPY. \COPY on the other hand, runs under the current $USER, and with that users environment. And \COPY can handle relative pathnames. The psql \COPY is accordingly much easier to use if it handles what you need.
With either of these you'll also need to have insert/update or select permission on the table in order to COPY to or from it.
From https://wiki.postgresql.org/wiki/COPY
The main difference is that COPY
will write the output file on the file system where the postgres server is running, not on the server where you execute COPY
. This will be the same, if you have a postgres server running on localhost, but can be big problem by more complex scenarios.
See also the documentation: http://www.postgresql.org/docs/9.3/static/sql-copy.html
and this answer: Save PL/pgSQL output from PostgreSQL to a CSV file
回答2:
You might be better writing a Python script that connects to the DB and runs the COPY command. Psycopg2 is the best adapter for this.
来源:https://stackoverflow.com/questions/32188644/can-i-use-copy-command-into-a-function-of-postgresql