Save PL/pgSQL output from PostgreSQL to a CSV file

后端 未结 18 2295
名媛妹妹
名媛妹妹 2020-11-22 11:56

What is the easiest way to save PL/pgSQL output from a PostgreSQL database to a CSV file?

I\'m using PostgreSQL 8.4 with pgAdmin III and PSQL plugin where I run que

18条回答
  •  误落风尘
    2020-11-22 12:04

    There are several solutions:

    1 psql command

    psql -d dbname -t -A -F"," -c "select * from users" > output.csv

    This has the big advantage that you can using it via SSH, like ssh postgres@host command - enabling you to get

    2 postgres copy command

    COPY (SELECT * from users) To '/tmp/output.csv' With CSV;

    3 psql interactive (or not)

    >psql dbname
    psql>\f ','
    psql>\a
    psql>\o '/tmp/output.csv'
    psql>SELECT * from users;
    psql>\q
    

    All of them can be used in scripts, but I prefer #1.

    4 pgadmin but that's not scriptable.

提交回复
热议问题