In other statistical programs, it’s possible to create a log file that shows the output issued as a result of a command. Is it possible to do something similar in SQL?
In particular, I’d like to have a single .sql file with many queries and to then output each result to a text file.
I’m using PostgreSQL and Navicat.
plpgsql function and COPY
One way would be to put the SQL script into a plpgsql function, where you can write the individual return values to files with
COPYand compile a report from intermediary results just like you need it.This has additional effect that may or may not be desirable. Like, you can grant or revoke permission to the whole function to arbitrary roles. Read about
SECURITY DEFINERin the manual. And the syntax will be verified when you save the function – however, only superficially (there are plans to change that in the future). More details in this answer on dba.SE.Basic example:
Of course, you need to have the necessary privileges in the database and in the file system.
Call it from the shell:
psql switching between meta commands and SQL
That’s right, 8 backslashes. Results from a double backslash that gets interpreted two times, so you have to double them two times.
I quote the manual about the meta-commands
\o:and
\\: