【问题标题】:dynamic portion of plpgsql functionplpgsql 函数的动态部分
【发布时间】:2017-05-18 07:44:28
【问题描述】:

我有一个函数可以遍历所有点并将它们与其他点进行比较(是的,我知道这不需要在 plpgsql 中完成 - 这是一个玩具 MWE)。函数返回x坐标最大的点:

create type point as (x integer, y integer);
create or replace function test() returns set of Point as
$$
declare
    p1 point;
    p2 point;
    bool integer;
begin
for p1 in select * from table loop
    bool := 0;
    for p2 in select * from table loop
        if p2.x > p1.x then bool :=1;
        exit;
        end if;
    end loop;
    if bool = 0 then return next p1;
    end if;
end loop;
end;
$$ language 'plpgsql';

有效。我想要做的是能够将表名作为函数的参数,我对将execute 语句放在哪里感到困惑。

【问题讨论】:

  • 动态查询结果循环请看postgresql.org/docs/current/static/…,构造为FOR-IN-EXECUTE
  • 另外,我知道这只是一个玩具示例,但 PostgreSQL 已经有一个 point type,它的用途与您刚刚创建的类型相同。不过它的语义略有不同,即您可以通过p1[0]p1[1] 访问其字段(在UPDATE 语句和/或PL/pgSQL 中设置它们也可以)。

标签: sql postgresql plpgsql


【解决方案1】:

https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html:

FOR-IN-EXECUTE 语句是遍历行的另一种方式:

t=# do
$$
declare
  _t text := 'pg_tables';
  _r record;
begin
  for _r in execute format('select * from %I limit 4',_t) loop
    raise info '%',_r.tablename;
  end loop;
end;
$$
;
INFO:  s141
INFO:  events
INFO:  tg_rep_que
INFO:  t4
DO

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2013-11-10
    • 2023-03-25
    • 2012-03-26
    • 2013-02-03
    • 1970-01-01
    相关资源
    最近更新 更多