addons_zz addons_zz - 1 month ago 6
SQL Question

How to print things to the postgres output console when running a SQL file?

How to print things to the postgres output console when running a SQL file?



I run my SQL files using this command:

PGPASSWORD=admin;
psql --host "localhost" --port 5432 --username "postgres" -d "aula21" < $1


I searched a lot and I found this strategy:

DO $$ BEGIN
RAISE INFO ' ';
RAISE INFO ' ';
RAISE INFO '1...';
END $$;

SELECT paciente.nome
FROM paciente
WHERE paciente.idade =
( SELECT MIN( paciente.idade )
FROM paciente );

DO $$ BEGIN
RAISE INFO ' nome ';
RAISE INFO '-----------------';
RAISE INFO 'Maria Aparecida';
RAISE INFO ' ';
RAISE INFO ' ';
RAISE INFO ' ';
RAISE INFO '2...';
END $$;

SELECT consulta.data, consulta.hora
FROM consulta
WHERE consulta.valor =
( SELECT MAX( consulta.valor )
FROM consulta );

DO $$ BEGIN
RAISE INFO ' Data hora valor';
RAISE INFO '"2002-03-21"; "09:00:00";122.0000';
RAISE INFO ' ';
RAISE INFO ' ';
RAISE INFO ' ';
RAISE INFO '3...';
END $$;


Generating the following output:

INFO:
INFO:
INFO: 1...
DO
nome
-----------------
Maria Aparecida
(1 row)

INFO: nome
INFO: -----------------
INFO: Maria Aparecida
INFO:
INFO:
INFO:
INFO:
INFO:
INFO:
INFO: 2...
DO
data | hora
------------+----------
2002-03-21 | 09:00:00
(1 row)

INFO: Data hora valor
INFO: "2002-03-21"; "09:00:00";122.0000
INFO:
INFO:
INFO:
INFO:
INFO:
INFO:
INFO: 3...
DO


But is there a better way to write it like this bellow?

print ' ';
print ' ';
print '1...';

SELECT paciente.nome
FROM paciente
WHERE paciente.idade =
( SELECT MIN( paciente.idade )
FROM paciente );

print ' nome ';
print '-----------------';
print 'Maria Aparecida';
print ' ';
print ' ';
print ' ';
print ' ';
print ' ';
print ' ';
print '2...';

SELECT consulta.data, consulta.hora
FROM consulta
WHERE consulta.valor =
( SELECT MAX( consulta.valor )
FROM consulta );

print ' Data hora valor';
print '"2002-03-21"; "09:00:00";122.0000';
print ' ';
print ' ';
print ' ';
print ' ';
print ' ';
print ' ';
print '3...';

Answer

I think you are looking for the \qecho psql command, see the documentation.

Comments