【问题标题】:Reduce duplication in postgres plpgsql function with CTE使用 CTE 减少 postgres plpgsql 函数中的重复
【发布时间】:2020-05-01 19:16:25
【问题描述】:

在 SQL 函数中,如果我这样做,我可以返回一个布尔值

with myquery as (delete from mytable where id = 'value1' returning 1)
select exists (select * from another_function('value2') where (select count(*) from myquery) > 0);

但在 plpgsql 函数中它不起作用并给出错误query has no destination for result data

在此函数中,如果实际从mytable 中删除了任何行,我想执行another_function。问题是我在重复整个select exists 部分,因为我在多个函数中使用它。

是否可以将更多的逻辑移到another_function 中?这样我就可以做这样的事情了?

with myquery as (delete from mytable where id = 'value1' returning 1)
select * from another_function('value2', myquery)

如何将 CTE 传递给函数,这样我就不需要在每次调用 another_function 时都重复 select existswhere (select count(*) from myquery) > 0)

【问题讨论】:

  • 我只是感到困惑。another_function 在一种情况下接受一个参数,在另一种情况下,第二个参数在哪里......什么?CTE?一个元组?我想你应该问一个新问题,其中包含有关您想要完成的任务的更多细节。

标签: sql postgresql plpgsql common-table-expression


【解决方案1】:

我希望辅助函数接受一个参数,例如从delete 返回的id。然后它看起来像:

with d as (
      delete from mytable
      where id = 'value1'
      returning id
     )
select another_function('value2', d.id)
from d;

这一次操作一个值,但这通常是人们想要的。如果你想一次性传入所有的 id,你可以使用一个数组:

with d as (
      delete from mytable
      where id = 'value1'
      returning id
     )
select another_function('value2', array_agg(d.id))
from d;

【讨论】:

  • 谢谢,你知道我怎样才能让我的问题中的第一个查询在定义为returns boolean 时不抛出query has no destination for result data 错误吗?它在使用 sql 函数而不是 plpgsql 时有效。
  • @user779159 。 . .如果这是在函数内部,则需要将值存储在某处。
  • 关于query has no destination for result data 错误,如果它是带有returns boolean 的常规sql 函数,我的第一个查询将起作用。但是,如果我将其更改为 plpgsql 函数,则会出现错误。通常,我可以通过执行return (select exists(.......)) 之类的操作从 plpgsql 函数返回布尔值。为什么这里不可能?如果我将整个 with 包裹在 return 中,我会得到 WITH clause containing a data-modifying statement must be at the top level
猜你喜欢
  • 2023-01-31
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多