I'd like to be able to print some debug information from sql script / function. Of course, I can do this by
RAISE NOTICE 'hello!'
But I also need to print a whole table's data. This doesn't work:
RAISE NOTICE '%' (SELECT * FROM table1)
Is it possible and how?
In this example “RAISE NOTICE 'value of a : %', a;” is used to print “NOTICE: value of a : 10” when the procedure is called. The severity level of NOTICE is used to print the message “value of a” and “%” is replaced by the value of variable “a,” which is 10 in this instance.
Use the RAISE statement to report messages and raise errors. RAISE level 'format' [, expression [, ...]]; Possible levels are DEBUG, LOG, INFO, NOTICE, WARNING, and EXCEPTION. EXCEPTION raises an error (which normally aborts the current transaction); the other levels only generate messages of different priority levels.
It is used in various parameters or options to produce an error message that is more informative and readable. When we are not specifying any level, then by default, the exception level is used in the raise statement. The exception level is aborted the current transaction with a raise statement in it.
PostgreSQL uses record type variables which simply act as placeholders for rows of a result set, similar to a row type variable. However, unlike row type variables, they do not have a predefined structure. Their structure is only determined after assigning a row to them.
The most straightforward way would be to iterate over the rows in a for loop
and use RAISE NOTICE
containing each column you're interested in interpolated in it.
i.e. something like:
FOR items IN SELECT * FROM table1 LOOP
RAISE NOTICE 'col1: %s, col2: %s', quote_ident(items.col1), quote_ident(items.col2);
END LOOP;
where items is declared as RECORD
.
Since postgres 9.3 you can use to_json()
to convert record into text suitable for notice,
RAISE NOTICE '%', to_json(record1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With