我正在尝试使用plpgsql在函数内部创建一个视图,它返回“小”表的x列,定义为(x integer,y integer)。
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关系,但我想使用变量名来调用视图。
任何帮助都将是
答案 0 :(得分:2)
您需要EXECUTE
动态查询:
RETURN QUERY EXECUTE 'SELECT x FROM ' || fullx;
答案 1 :(得分:2)
为select
使用动态SQL(正如您用于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;