dblink returns SQL Error [42703]: ERROR: column "xy" does not exist

dblink returns SQL Error [42703]: ERROR: column "xy" does not exist

谁能告诉我为什么会出现这个错误以及我该如何解决它?

我有这样的功能:

CREATE OR REPLACE FUNCTION custom.dblink_function_v21()
 RETURNS TABLE(name character varying, service character varying, scopes character varying)
 LANGUAGE plpgsql
AS $function$
DECLARE
    var_req TEXT;

    rec_key record;
    cur_key CURSOR FOR Select * from dblink(
'host=server1
user=user1
password=pw1
dbname=db1
port=5433',
'
select s.id,s.name,s.host from servers s where s.id IN (465,325) order by s.name
') as (srv character varying,name character varying, host character varying);

BEGIN
open cur_key;
loop
   fetch cur_key into rec_key;
   EXIT WHEN NOT FOUND;
  var_req := 'Select * from dblink(
''host=' || rec_key.host || '
user=user2
password=pw2
dbname=db2'',
''
select
' || rec_key.name || ' as name ,
es.name as service,
es.scopes::varchar as scopes
from services es
'') as (srv varchar,service varchar,scopes varchar);
';
return query execute var_req; 

 end loop;
close cur_key;
END
$function$
;

当我用 select * from custom.dblink_function_v21() 调用它时,出现此错误:

SQL Error [42703]: ERROR: column "dba01" does not exist
  Where: Error occurred on dblink connection named "unnamed": could not execute query.
PL/pgSQL function custom.dblink_function_v21() line 43 at RETURN QUERY

dba01 不是列。这是我在列名中的第一个值。

如果我也改变 ' || rec_key.name || ' ' || rec_key.srv || ' 我突然工作了。但我不想要 return 中的服务器 ID,我想要名称。他们都有相同的数据类型和一切,所以我不知道是什么问题。

我一直在疯狂地尝试不同的东西,但没有任何效果..

使用 postgres v.10

这是您创建的 select 语句:

select XXX as name , es.name as service, es.scopes::varchar as scopes from services es

其中 XXX 是 rec_key.name 的值 - 在后一种情况下是 rec_key.srv 的值。

在前一种情况下,语句的计算结果为:

select dba01 as name , es.name as service, es.scopes::varchar as scopes from services es

但在后一种情况下:

select 100 as name , es.name as service, es.scopes::varchar as scopes from services es

在前一种情况下,由于列 dba01 不存在而发出错误。在后一种情况下,数字 100 被 select 编辑为名称。这是一个完全有效的语句,因为它不会被解释为列名。

如果您想 select 文本值“dba01”作为“名称”列,您可以将该部分更改为:

''' || rec_key.name || '''::text as name ,

问候,Bjarni