关系不存在PLPGSQL

时间:2017-05-19 17:31:20

标签: sql postgresql plpgsql dynamic-sql

我正在尝试使用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关系,但我想使用变量名来调用视图。

任何帮助都将是

2 个答案:

答案 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;