ORACLE中的CTE和表更新

hir*_*lau 6 sql oracle common-table-expression

在我最终通过更新表中的列来存储结果之前,我想要运行许多复杂的逻辑.我收到一个错误,并且能够将其归结为:

with my_cte as
(
  select x,ix from y
)
update z
set mycol = (select x from my_cte where z.ix = my_cte.ix)
Run Code Online (Sandbox Code Playgroud)

然而,这给出了错误:

Error at line 4:
ORA-00928: missing SELECT keyword
set mycol = (select x from my_cte where z.ix = my_cte.ix)
Run Code Online (Sandbox Code Playgroud)

这是否意味着CTE不能与更新一起使用,因为以下查询工作正常:

update z
set mycol = (select x from y where y.ix = my_cte.ix)
Run Code Online (Sandbox Code Playgroud)

使用12c企业版12.1.0.2.0版

编辑:

解决这个问题一段时间后,获得合理性能的唯一方法是使用MERGE子句(仍然使用CTE,如下面的答案).

merge into z using (
  with my_cte as (
    select x,ix from y
  )
)
on (
  my_cte.ix = z.ix 
)
when matched then
update set mycol = my_cte.x
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 9

在Oracle中,CTE是SELECT不是的一部分UPDATE:

update z
    set mycol = (
          with my_cte as (
             select x, ix
             from y
          )
          select x from my_cte where z.ix = my_cte.ix
         );
Run Code Online (Sandbox Code Playgroud)