有时在 with 块中使用 dml 很有用,例如
with
ins as (
insert into some_table(...)
),
upd as (
update some_table set ...
)
select
这在 sql 中工作得很好,但尝试在 plpgsql 中使用此构造会给出
ERROR: query has no destination for result data
。
尝试用
select
替换 perform
会得到 syntax error at or near "perform"
。
尝试将所有内容都放在外部
perform
中会得到WITH clause containing a data-modifying statement must be at the top level
。
当然,我可以将最后一个 dml-with 块从
with
中取出
with
ins as (
insert into some_table(...)
)
update some_table set ...
或写类似
delete from some_table where false
,
但也许有一些更优雅的解决方案?
根据错误信息,你只需要把select语句的返回结果赋给一个变量即可(因为它总是有一个返回值,至少是NULL),就像这样
do $$
declare res varchar;
begin
with
ins as (
insert into some_table(...)
),
upd as (
update some_table set ...
)
select into res;
raise notice 'Returning value from select statement %', res;
end $$;