1

I'm novice in PostgreSQL 8.4, I'm trying to export csv files from temporary tables.

As I wrote

SET client_encoding TO 'SJIS';
\copy temp_table TO 'temp_table.csv' WITH CSV HEADER;
SET client_encoding TO 'UTF8';

However, this code returns error like

\copy: parse error at ";"

Please help me... Thank you in advance!

tomohitoy
  • 547
  • 2
  • 5
  • 5

2 Answers2

1

\copy is an internal "meta-command" of the psql command-line client (8.4-specific documentation), not an SQL statement.

It is designed to look very similar to an SQL COPY statement, but doesn't require (or accept) a terminating ;, since all meta-commands are terminated by a newline or \ (which is taken as the start of a new meta-command).

So you should be able to simply remove the character it's complaining about:

SET client_encoding TO 'SJIS';
\copy temp_table TO 'temp_table.csv' WITH CSV HEADER
SET client_encoding TO 'UTF8';

See also this answer about COPY and \copy.

Community
  • 1
  • 1
IMSoP
  • 65,743
  • 7
  • 83
  • 127
  • You have given a nice answer in that link. Given a +1 there. Good read. As well I have edited my answer based on your suggestion and removed `;`. – Rahul Jun 11 '14 at 11:58
  • Thank you very much!! I do in this way and I can export csv files. And the link is very nice. I should learn about the difference between `COPY` and `\copy`. I confused about that. – tomohitoy Jun 11 '14 at 12:14
  • @IMSoP , if i want to call these 3 lines from a shell script then how to call it ? back slash before copy command is creating error from shell script. – abhisek May 29 '19 at 11:35
-1

Per Documentation the correct syntax is

COPY { table_name [ ( column_name [, ...] ) ] | ( query ) }
    TO { 'filename' | PROGRAM 'command' | STDOUT }
    [ [ WITH ] ( option [, ...] ) ]

With that, your COPY statement should look like below, remove the \ and WITH

SET client_encoding TO 'SJIS';
copy temp_table TO 'temp_table.csv' CSV HEADER;
SET client_encoding TO 'UTF8';

(OR) Removing the ; as suggested by @IMSoP

\copy temp_table TO 'temp_table.csv' WITH HEADER
Rahul
  • 71,392
  • 13
  • 57
  • 105