
[英]PostgreSQL: Is there a query or script for inserting data from database to another database?
[英]postgresql: USING CURSOR for extracting data from one database and inserting them to another
这是使用游标的另一种算法,但我很难修复其错误...
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;
为什么不自己尝试,根据错误,您可以尝试逐步解决它们!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.