Postgresql: dblink in Stored Functions

為{幸葍}努か 提交于 2019-12-11 00:03:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!