【问题标题】:Run sql function from EXISTS query using postgres CTE使用 postgres CTE 从 EXISTS 查询运行 sql 函数
【发布时间】:2020-05-02 09:55:03
【问题描述】:

在 postgres sql 函数中,我只想在 CTE 返回任何行时运行function_update。此查询适用于此。

with common_table as (select 1 where true) select function_update('value') from common_table

但是,如果我还想返回 function_update 是否更新了任何行,那么它不起作用。该函数确实返回 truefalse,具体取决于 CTE 是否返回任何行,但 function_update 似乎没有运行。

with common_table as (select 1 where true) select exists(select function_update('value') from common_table)

function_update 就像update mytable set column1 = 'changed' where column2 = arg_value 这样简单。 mytable 在我运行上面的第一个查询而不是第二个查询时得到更新。为什么这没有按预期工作,我需要更改什么?

【问题讨论】:

  • function_update() 返回什么?
  • 这是一个带有returns void的函数。不返回任何内容,只是更新一行。

标签: sql postgresql common-table-expression


【解决方案1】:

为什么没有按预期工作

Exists 检查存在和查询优化器不必执行该功能。以下示例表明我们可以预期除以 0 错误:

select 1 WHERE EXISTS (SELECT 1/0);
-- 1

db<>fiddle demo


我需要改变什么?

一种方法是强制实现:

select 1 WHERE EXISTS (WITH cte AS MATERIALIZED (SELECT 1/0) SELECT * FROM cte)
-- division by 0

db<>fiddle demo

【讨论】:

  • 如果存在 CTE,如何获得想要的更新效果?
猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 2012-12-07
  • 2022-01-17
  • 2016-11-01
  • 1970-01-01
  • 2022-11-30
  • 2011-10-10
相关资源
最近更新 更多