问题
I want to insert top 20 ROWS from a table tbl_A in db_A to tbl_B in db_B.
The schema for tbl_A and tbl_B is:
CREATE TABLE <tbl_name> (
id serial PRIMARY KEY,
int a,
int b
);
I have some questions related to following queries
psql db_A
SELECT dblink_connect("dbname=db_B");
SELECT dblink_open('curse', 'SELECT id, a, b FROM tbl_B');
INSERT INTO tbl_A (SELECT id, a, b FROM dblink_fetch('curse', 20) AS (s_is int, s_a int, s_b int)) RETURNING a;
- Can I put the following statements in stored procedure:
- Is it possible to create a stored procedure of above three statements combined and create a prepared statement of that procedure.
I would be highly grateful if someone can comment on how good a practice is it to use cursor, or using dblink inside stored procedures or any other ways that above is achieved more elegantly.
回答1:
There's much easier way:
Connect to db_B and execute the following:
CREATE OR REPLACE FUNCTION dblink(text, text)
RETURNS SETOF record AS
'$libdir/dblink', 'dblink_record'
LANGUAGE 'c' VOLATILE STRICT
COST 1
ROWS 1000;
ALTER FUNCTION dblink(text, text) OWNER TO postgres;
GRANT EXECUTE ON FUNCTION dblink(text, text) TO public; -- or whatever
INSERT INTO tbl_B select * from
(SELECT * from dblink('hostaddr=localhost port=5432 dbname=db_A user=postgres password=postgres',
'select id, a, b from tbl_A limit 20 '
)
t(
id integer,
a integer,
b integer
)) as q;
来源:https://stackoverflow.com/questions/6148534/postgresql-dblink-in-stored-functions