我想从db_A中的表tbl_A到db_B中的tbl_B插入前20个ROWS。
tbl_A和tbl_B的模式是:
CREATE TABLE <tbl_name> (
id serial PRIMARY KEY,
int a,
int b
);
我有一些与以下查询有关的问题
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;
如果有人可以评论使用游标的实践有多好,或者在存储过程中使用dblink或者更优雅地实现上述任何其他方式,我将非常感激。
答案 0 :(得分:4)
有更简单的方法:
连接到db_B并执行以下命令:
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;