在postgres sql函数中,我只想在CTE返回任何行时运行function_update
。此查询适用于此。
with common_table as (select 1 where true) select function_update('value') from common_table
但是,如果我还想返回function_update
是否更新了任何行,那么它就不起作用。函数确实正确地返回了true
或false
,这取决于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
会得到更新。为什么这不起作用,我需要改变什么?
为什么这不能像预期的一样工作
Exists检查是否存在,查询优化器不必执行该函数。下面的例子表明,我们可以预期一个除以0的错误:
select 1 WHERE EXISTS (SELECT 1/0);
-- 1
db<>小提琴演示
我需要更改什么?
一种方法是强制物化:
select 1 WHERE EXISTS (WITH cte AS MATERIALIZED (SELECT 1/0) SELECT * FROM cte)
-- division by 0
db<>小提琴演示