patternsqlModerate
Insert RECORD into a table in a trigger function
Viewed 0 times
triggerinsertintofunctionrecordtable
Problem
I would like to insert a RECORD data type variable (NEW variable) into a table in a trigger. What would the SQL look like?
The following attempts were unsuccessful:
The following attempts were unsuccessful:
EXECUTE 'INSERT INTO my_table VALUES ' || NEW;
EXECUTE 'INSERT INTO my_table VALUES ' || NEW.*;
EXECUTE 'INSERT INTO my_table SELECT * FROM ' || NEW;Solution
Actually, you do not have to expand the record manually. As long as number, sequence and types of columns match between the two tables, you can use this much simpler form:
Since your table name seems to be stable, you do not even need dynamic SQL with
The parentheses are required for a composite type to make the syntax unambiguous.
Ask yourself what may change in your app in the future:
-
If the target table should stay in sync with the source table (or target and source are the same), then it's better not to list columns explicitly.
-
If you want to select only certain columns and do not want to change that with possible updates to the source or target table, it's better to supply a column list.
EXECUTE 'INSERT INTO my_table SELECT ($1).*'
USING NEW;Since your table name seems to be stable, you do not even need dynamic SQL with
EXECUTE. Just a plain INSERT:INSERT INTO my_table SELECT (NEW).*The parentheses are required for a composite type to make the syntax unambiguous.
Ask yourself what may change in your app in the future:
-
If the target table should stay in sync with the source table (or target and source are the same), then it's better not to list columns explicitly.
-
If you want to select only certain columns and do not want to change that with possible updates to the source or target table, it's better to supply a column list.
Code Snippets
EXECUTE 'INSERT INTO my_table SELECT ($1).*'
USING NEW;INSERT INTO my_table SELECT (NEW).*Context
StackExchange Database Administrators Q#58455, answer score: 19
Revisions (0)
No revisions yet.