postgresql + dblink + insert with return

时间:2016-04-20 17:10:43

标签: postgresql insert dblink

我需要在远程数据库中插入一条记录并插入id。我做错了什么?

DECLARE

ticketvar mytable%rowtype;

SqlCommand TEXT;

BEGIN    

ticketvar.c1 := somevalue;
ticketvar.c2 := somevalue;

SqlCommand := 'INSERT INTO mytable ( c1, c2)  VALUES (||ticketvar.c1||, ||ticketvar.c2||) returning tid';

tid =  (select *  from dblink('mydatawrapper',SqlCommand)  AS t1(bigint tid)  );

...

它引发错误`

错误:缺少表" ticketvar"`

的FROM子句条目

使用select语句,一切正常:

result = (select *  from dblink('mydatawrapper','SELECT tid FROM mytable WHERE c1='||c1||'')  AS t1(bigint tid) );

2 个答案:

答案 0 :(得分:0)

http://www.postgresonline.com/journal/archives/44-Using-DbLink-to-access-other-PostgreSQL-Databases-and-Servers.html

您需要连接,因为您可以像returning一样使用sqlCommand执行插入。

回答这个问题。对我来说,看起来你正在使用plSQL - 简单的SQL就足够了。

答案 1 :(得分:0)

对我来说适用于外部数据包装器和dblink的示例:

-- if text field has apostrophes:
value2 = replace(value2,'''','''''');

q1 = 'INSERT INTO foreign_table1( field1,field2,field3) 
      VALUES ('||value1||','''||value2||''', now()) RETURNING id';

SELECT * FROM dblink('foreign_server', q1) 
         AS foreign_rec(id INTEGER) INTO foreign_table1_id;