【问题标题】:How to "PERFORM" CTE queries in PL/pgSQL?如何在 PL/pgSQL 中“执行”CTE 查询?
【发布时间】:2022-02-09 05:45:30
【问题描述】:

我试图在下面的代码示例中模拟我的问题。在下面的代码中,我在一个过程中执行select * from test。众所周知,我们必须为此使用perform 关键字。这很好用:

perform * from test;

但是,如果我尝试将这个简单的查询重写为 CTE,我将无法使其正常工作。我收到语法错误。

with test_as_cte as(select * from test) perform * from test_as_cte;

这可能吗?什么是正确的语法?我尝试了几种替代方法并浏览了文档,但到目前为止没有任何成功。

(请注意,这只是解释我的问题的一个示例。我知道这些查询没有任何意义。)

create table test
(
    key int primary key  
);

create function test() returns trigger as
$$
begin
    raise notice 'hello there';
    -- this does work
    perform * from test;
    -- this doesn't work
    with test_as_cte as(select * from test) perform * from test_as_cte;
    return new;
end;
$$
language plpgsql;

create trigger test after insert on test for each row execute procedure test();

insert into test(key) select 1;

【问题讨论】:

  • @ErwinBrandstetter >>有时评估表达式或 SELECT 查询但丢弃结果很有用,例如在调用具有副作用但没有有用结果值的函数时。所以整个 perform 子句没有意义。在这种情况下。所以它就像begin raise notice 'hello there'; return new; end

标签: postgresql triggers plpgsql common-table-expression


【解决方案1】:

尝试:

perform (with test_as_cte as(select * from test) select * from test_as_cte);

我永远不会认为您可能需要 CTE 并忽略结果,但如果您需要,将执行视为“选择不返回”逻辑会导致上述语义。或perform * from (CTE) 或类似的

【讨论】:

  • 谢谢。这确实有效。问题是,我抽象得太多了。我会问一个新问题。
  • 我显然要等 90 分钟 :)。我将在今天晚些时候添加它。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
相关资源
最近更新 更多