Copy data between two tables in PostgreSQL using dblink.sql

前端 未结 1 980
暗喜
暗喜 2021-01-14 15:58

I am using PostgreSQL 9.1. I need to transfer required columns from one table of one database into another table of another database, but not schema.
I found that

相关标签:
1条回答
  • 2021-01-14 16:35

    After you have installed the package into your system as detailed in the related question install the extension dblink into your database (the one you are running this code in, the foreign db does not need it):

    CREATE EXTENSION dblink;
    

    You can find code examples in the manual.
    Here is a simple version of what I use to copy data between dbs: First, create a FOREIGN SERVER

    CREATE SERVER mydb
    FOREIGN DATA WRAPPER postgresql
    OPTIONS (hostaddr '111.111.111.111',port '5432',dbname 'mydb');
    

    FOREIGN DATA WRAPPER postgresql was pre-installed in my case.
    Then create function that opens a connection, removes old data (opotional), fetches new data, runs ANALYZE and closes the connection:

    CREATE OR REPLACE FUNCTION f_tbl_sync()
      RETURNS text AS
    $BODY$
    SELECT dblink_connect('mydb');  -- USER MAPPING for postgres, PW in .pgpass
    
    TRUNCATE tbl;  -- optional
    
    INSERT INTO tbl
    SELECT * FROM dblink(
      'SELECT tbl_id, x, y
       FROM   tbl
       ORDER  BY tbl_id')
        AS b(
     tbl_id int
    ,x int
    ,y int)
    
    ANALYZE tbl;
    
    SELECT dblink_disconnect();
    $BODY$
      LANGUAGE sql VOLATILE;
    
    0 讨论(0)
提交回复
热议问题