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

postgresql:使用游标从一个数据库提取数据并将其插入另一个数据库,postgresql,plpgsql,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

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

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;

抱歉,我不能真正理解学生%rowtype和部分->“| | quote|nullablerec.fname | |”、“| | quote| nullablerec.lname | |”、“| | quote| nullablerec.mname |”,“| | quote | nullablerec.address | | |”您能解释一下这一部分吗?student%rowtype是自动创建的记录结构类型,格式与student表相同。quote_nullable接受字符串值并输出引用值,适合包含在SQL语句中。