As Henrik wrote, you can use dblink to connect the remote database and the selection result. For example:
psql dbtest CREATE TABLE tblB (id serial, time integer); INSERT INTO tblB (time) VALUES (5000), (2000); psql postgres CREATE TABLE tblA (id serial, time integer); INSERT INTO tblA SELECT id, time FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB') AS t(id integer, time integer) WHERE time > 1000; TABLE tblA; id | time
PostgreSQL has a pseudo-type record (only for function argument or result type) that allows you to query data from another (unknown) table.
Edit:
You can do this as a prepared statement if you want, and it also works:
PREPARE migrate_data (integer) AS INSERT INTO tblA SELECT id, time FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB') AS t(id integer, time integer) WHERE time > $1; EXECUTE migrate_data(1000);
Edit (yes, other):
I just saw your revised question (closed as duplicate or just very similar to this).
If my understanding is correct (postgres has tbla and dbtest has tblb, and you want remote insert with local insert , and not remote select with local insert as above):
psql dbtest SELECT dblink_exec ( 'dbname=postgres', 'INSERT INTO tbla SELECT id, time FROM dblink ( ''dbname=dbtest'', ''SELECT id, time FROM tblb'' ) AS t(id integer, time integer) WHERE time > 1000;' );
I do not like this nested dblink, but AFAIK I cannot reference tblB in the dblink_exec body. Use LIMIT to specify the top 20 lines, but I think you need to sort them using the ORDER BY clause.
Grzegorz Szpetkowski May 21 '11 at 17:53 2011-05-21 17:53
source share