简体   繁体   中英

Postgres Psql to file

I have a bash script, with a call to PSQL, which executes a query, and then using a WHILE loop, I print the output to a file. Something like:

psql -U zrec -d zrec -t -c "SELECT .........;" \    | while read -a Record; do
  printf "${Record[0]},${Record[1]}\n"  >> /tmp/file.csv
done

The query has grown into a very large query. Also, I now need to pass a date variable to the query. So, I'm thinking to take this hard coded query, and put it into a.sql file, call it, pass the date variable, and print the output to a file.

Oracle makes this easy with SPOOL and &1, etc.......

Is there a way I can:

  1. Call the bash script
  2. Have the script call my_query.sql, and pass it a date parameter
  3. Put the query output into a file

Seems like it should be simple, but is proving not to be.

If you want to generate a csv file, don't use spool or something similar, use \copy . No need to loop.

Something like:

\copy (SELECT ....) to '/tmp/file.csv' with (format csv, header true)

It's typically easier to put anything that is longer than a few words into a separate SQL script rather than passing it using -c "..." which also opens up many nested quoting problems.

So if you put the above into a file eg export.sql , all you need is:

psql -U zrec -d zrec -f export.sql`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM