如何在PL/pgSQL中执行CTE查询?

12

我在下面的代码示例中尝试模拟我的问题。在下面的代码中,我在一个存储过程中执行了 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;

请考虑以下跟进问题:https://dev59.com/eXANtIcB2Jgan1znrhmp - Erwin Brandstetter
有时候,评估表达式或SELECT查询但丢弃结果是很有用的,例如在调用具有副作用但没有有用结果值的函数时。因此,在这种情况下,整个perform子句都没有意义。所以它就像这样: begin raise notice 'hello there'; return new; end - jian
1个回答

12

尝试:

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

我从未想过你会需要CTE并忽略结果,但如果需要的话,把它想象成“选择无返回”逻辑可以得到上面的语义。或者使用perform * from (CTE)或类似方法。


谢谢。确实有效。问题是,我抽象化得有点过度了。我会提出一个新的问题。 - Caroline Kwerts
显然我必须等待90分钟: )。我今天稍后会添加它。再次感谢。 - Caroline Kwerts
请参见:https://dev59.com/TaPia4cB1Zd3GeqPtyNv - Caroline Kwerts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接