postgresql - 带有 PERFORM 数据修改 CTE 查询的 Postgres plpgsql

标签 postgresql plpgsql common-table-expression

我试图在下面的代码示例中模拟我的问题。在下面的代码中,我正在一个过程中执行 delete from test2 操作。这很好用:

但是,在我的例子中,这个 delete 是一个相当复杂的 CTE 的一部分,有几个更新和插入(没有选择,所以我添加了一个虚拟的 select 1 作为主查询)。让我们模拟一下:

with my_cte as(delete from test2) select 1

现在,正如我们所知,我们必须使用 perform 关键字来执行:

perform (with my_cte as(delete from test2) select 1);

我收到以下错误:

ERROR: WITH clause containing a data-modifying statement must be at the top level

这是plpgsql的限制吗?

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

create table test
(
    key int primary key  
);

create table test2
(
    key int primary key
);

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

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

insert into test(key) select 1;

最佳答案

您可以使用 CTE 组合多个 DELETE、INSERT、UPDATE 返回查询。而且你不需要为此执行,例如:

t=# begin; do $$ begin with d as (delete from s133 returning *) insert into s133 select * from d; raise info '%',(select count(1) from s133);
end; $$; commit;
BEGIN
Time: 0.135 ms
INFO:  4
DO
Time: 0.469 ms
COMMIT
Time: 0.887 ms
t=# select count(1) from s133;
 count
-------
     4
(1 row)

这里我删除了四行并在 CTE 中将它们插入回去

关于postgresql - 带有 PERFORM 数据修改 CTE 查询的 Postgres plpgsql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44908442/

相关文章:

sql - 一起使用 INSERT 和 WITH 语句时出错

sql - 选择结果作为用户定义的表参数函数中的参数

ruby-on-rails - docker-compose rails rake db :reset fails, "cannot drop the currently open database"

postgresql - 将 aws rds 只读副本提升到数据库实例是否会维护新数据库实例的复制?

sql - 选择相关表中具有两个值的行

ruby-on-rails - 如何将 Rails 中的_column 从字符串更改为 jsonb?

sql - 当我有很多记录时,Postgres 函数返回一条记录?

调试 PL/Python 函数

postgresql - 创建创建新序列的过程/函数

postgresql - 保护 CTE 中的关键资源表(WITH 子句)