【问题标题】:Relation does not exist PLPGSQL关系不存在 PLPGSQL
【发布时间】:2017-10-19 22:14:44
【问题描述】:

我正在尝试使用 plpgsql 在函数内部创建一个视图,它返回定义为 (x integer,y integer) 的“小”表的 x 列。

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');

它返回“relation fullx 不存在”

我明白是因为没有fullx关系,但是我想用变量名来调用视图。

任何帮助将是

【问题讨论】:

    标签: sql postgresql plpgsql dynamic-sql


    【解决方案1】:

    你需要EXECUTE你的动态查询:

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

    【讨论】:

    • 非常感谢如果我返回一个整数而不是 setof 整数可以做什么? foreg 返回查询执行格式('select count(x) from %I', fullx);但返回查询仅适用于 setof
    【解决方案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;
    

    【讨论】:

    • 非常感谢,如果我返回一个整数而不是 setof 整数,该怎么办? foreg 返回查询执行格式('select count(x) from %I', fullx);但返回查询仅适用于 setof
    • 在这种情况下,您可以声明一个整数变量execute ... into variable 并返回它。
    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2017-04-20
    • 2022-01-22
    • 2021-03-30
    • 2017-04-22
    • 2017-07-05
    • 2023-04-03
    相关资源
    最近更新 更多