CREATE OR REPLACE FUNCTION gesio(_tbl_in anyelement, _tbl_out regclass)
RETURNS void AS
$func$
BEGIN
FOR _tbl_in IN EXECUTE
format('SELECT * FROM %s', pg_typeof(_tbl_in))
LOOP
-- do something with record
EXECUTE format('INSERT INTO %s SELECT $1.*', _tbl_out)
USING _tbl_in;
END LOOP;
END
$func$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION gesio(_tbl_in anyelement, _tbl_out regclass)
RETURNS void
LANGUAGE plpgsql AS
$func$
BEGIN
FOR _tbl_in IN EXECUTE
format('SELECT * FROM %s', pg_typeof(_tbl_in))
LOOP
-- do something with record
EXECUTE format('INSERT INTO %s SELECT $1.*', _tbl_out)
USING _tbl_in;
END LOOP;
END
$func$;
t
and t1
being the tables with identical schema.
Note that the The polymorphic parameter (anyelement
) is only needed if you need it's value or data type for the computation in the function body. Else you can simplify like demonstrated in this later answer:
Implicit cursor of a
FOR
loopImplicit cursor of aFOR
loop instead of explicit cursor. That's generally preferable.VALUES
can take a row type directly.VALUES
can take a row type directly.
An obstacle to overcome is that variables inside the function cannot be defined as polymorphic type anyelement
(yet). This related answer on SOThis related answer on SO explains the solution. Provides a workaround for older versions, too.
The value of the first parameter is discardeddiscarded. UseJust use NULL
.
Consider this related answer on SO with more detailsthis related answer on SO with more details. The most interesting part being the last chapter Various complete table types"Various complete table types".
SQL Fiddle demo.db<>fiddle here
Old sqlfiddle