I have a problem on creating PostgreSQL (9.3) trigger on update table. I want set new values in the loop as
EXECUTE 'NEW.'|| fieldName || ':=''some prepend data'' || NEW.' || fieldName || ';';
where fieldName is set dynamically. But this string raise error
ERROR: syntax error at or near "NEW"
How do I go about achieving that?
You can implement that rather conveniently with the
hstore
operator#=
:Make sure the additional module is installed properly (once per database), in a schema that's included in your
search_path
:Trigger function:
Trigger (reuse the same func for multiple tables):
Closely related with more explanation and advice:
I found a working solution: trigger should execute after insert/update, not before. Then desired row takes the form
fieldName and fieldValue I get in the next way:
Your problem is that
EXECUTE
can only be used to execute SQL statements and not PL/pgSQL statements like the assignment in your question.You can maybe work around that like this:
Let's assume that table
testtab
is defined like this:Then a trigger function like the following will work:
I used hard-coded
id
andval
in my example, but that is not necessary.