2017-05-19 91 views
1

我想在函数内部使用plpgsql创建一个视图,该视图返回定义为(x integer,y integer)的“small”表的x列。不存在关系PLPGSQL

create or replace function skyline_naive2(dataset text) returns setof integer as 
$$ 
declare 
    fullx text; 
begin 
    fullx = dataset||'_skyline_naive2'; 
    execute format('create view %s as select x,y from %s',fullx,dataset); 
    return query select x from fullx; 
end 
$$ language plpgsql; 

select * from skyline_naive2('small'); 

它返回“关系fullx不存在”

我明白,这是因为没有fullx关系,但我想打电话给使用变量名的观点。

任何帮助将是

回答

2

使用动态SQL select(因为你已经使用了create):

create or replace function skyline_naive2(dataset text) returns setof integer as 
$$ 
declare 
    fullx text; 
begin 
    fullx = dataset||'_skyline_naive2'; 
    execute format('create view %I as select x,y from %I',fullx,dataset); 
    return query execute format('select x from %I', fullx); 
end 
$$ language plpgsql; 
+0

非常感谢 如果我返回一个整数而不是setof整数可以做什么? foreg 返回查询执行格式('从%I'选择count(x),fullx); 但返回查询仅适用于集合 –

+0

在这种情况下,您可以声明一个整型变量'execute ... into variable'并将其返回。 – klin

2

您需要EXECUTE动态查询:

RETURN QUERY EXECUTE 'SELECT x FROM ' || fullx; 
+0

非常感谢也可以做什么,如果我返回一个整数,而不是setof整数? foreg返回查询执行格式('从%I'选择count(x),fullx);但返回查询只适用于设置 –