postgresql:使用游标从一个数据库中提取数据并将其插入到另一个数据库中

标签 postgresql plpgsql

这是另一种使用光标的算法,但我很难修复它的错误......

CREATE OR REPLACE FUNCTION extractstudent()
RETURNS VOID AS 
$BODY$
DECLARE
    studcur SCROLL cursor FOR SELECT fname, lname, mname, address FROM student;
BEGIN    
    open studcur; 

    Loop
    --fetching 1 row at a time
    FETCH First FROM studcur;
    --every row fetched is being inserted to another database on the local site
    --myconT is the name of the connection to the other database in the local site
    execute 'SELECT * from dblink_exec(''myconT'', ''insert into temp_student values(studcur)'')';
    --move to the next row and execute again
    move next from studcur;
    --exit when the row content is already empty
    exit when studcur is null;
    end loop;

    close studcur;    

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION extractstudent() OWNER TO postgres;

最佳答案

您很少需要在 postgresql 或 pl/pgsql 中显式使用游标。您所编写的内容看起来很像 SQL Server 游标循环构造,但您不需要这样做。另外,您可以使用“PERFORM”而不是“EXECUTE”来运行查询并丢弃结果:这将避免每次重新解析查询(尽管它无法避免 dblink 每次解析查询)。

你可以做更多这样的事情:

DECLARE
  rec student%rowtype;
BEGIN
  FOR rec IN SELECT * FROM student
  LOOP
    PERFORM dblink_exec('myconT',
      'insert into temp_student values ('
          || quote_nullable(rec.fname) || ','
          || quote_nullable(rec.lname) || ','
          || quote_nullable(rec.mname) || ','
          || quote_nullable(rec.address) || ')');
  END LOOP;
END;

关于postgresql:使用游标从一个数据库中提取数据并将其插入到另一个数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5334645/

相关文章:

sql - 带有正则表达式的自定义 postgreSQL 域以接受一组特定的字符串

sql - 在 postgres 中输入同一张表?

postgresql - 在触发器函数中使用动态表名插入

sql - PostgreSQL 9.5 : Logging exception handling

postgresql - unaccent() 不适用于 plpgsql 动态查询中的希腊字母

plpgsql - Postgresql-创建函数

mysql - Sequelize 原始查询以将数据作为数组返回

sql - 使用 PERFORM 将一串 SELECT 语句插入到临时表中

postgresql - "SELECT * FROM $1"准备语句错误到 : error: syntax error at or near "$1"

postgresql - 从 INSERT 或 SELECT 获取 id