Unfortunately it is not easy to parse the RECORD
type using PL/pgSQL. If the structure of the tables passed in arguments are always the same as some other table or type you could use this type directly instead of RECORD
, and then use the following:
DECLARE
recCurs table_or_type;
...
BEGIN
...
OPEN recCurs FOR EXECUTE ...
...
EXECUTE 'INSERT INTO ' || events_table_out || ' VALUES(($1).*)'
USING recCurs;
...
But this will not work with RECORD
type. The only solution I can think of is creating the query by hand. But PL/pgSQL gives no way to dynamically get the keys of an RECORD
type. So you have to use some external tools. The best (in my opinion) for this kind of job is the hstore
extension. Once installed you can create it on your database (the following works only on 9.1+, for earlier you should do it by hand):
CREATE EXTENSION hstore;
Now. You are able to convert a RECORD
type to an hstore
type, using hstore(recCurs)
, and so you can dynamically iterate over its keys and values with the each
function:
DECLARE
recCurs record;
kv record;
v_cols text;
v_vals text;
BEGIN
...
OPEN recCurs FOR EXECUTE ...
...
-- 1. do something with rec
-- 2. insert the rec into events_table_out:
v_cols := '';
v_vals := '';
FOR kv IN SELECT * FROM each(hstore(recCurs)) LOOP
v_cols := v_cols || kv.key || ',';
v_vals := v_vals || quote_nullable(kv.value) || ',';
END LOOP;
v_cols := substr(v_cols, 1, length(v_cols)-1);
v_vals := substr(v_vals, 1, length(v_vals)-1);
EXECUTE 'INSERT INTO ' || events_table_out
|| '(' || v_cols || ') '
|| 'VALUES (' || v_vals || ')';
...
Of course, it will only work if the table "pointed" by events_table_out
has all the columns that events_table_in
has (the first can have more columns).
RESUMING: always you want some dynamic key/value data-type on PL/pgSQL, and RECORD
is not enough, the hstore
can be used.