2016-10-31 176 views
4

在我最終通過更新表中的列來存儲結果之前,我想要運行很多複雜的邏輯。我得到一個錯誤,並且已經能夠得到它歸結爲:ORACLE中的CTE和表更新

with my_cte as 
(
    select x,ix from y 
) 
update z 
set mycol = (select x from my_cte where z.ix = my_cte.ix) 

然而,這給出了錯誤:

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

這是否僅僅意味着熱膨脹係數不能與更新,因爲下面的查詢作品使用精細:

update z 
set mycol = (select x from y where y.ix = my_cte.ix) 

使用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 
+0

CTE仍然可以用作更新子查詢,如下所示:https://stackoverflow.com/a/39534514/603516 – Vadzim

回答

6

在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 
     ); 
1

如果z.ix - 是主要凱y.ix - 爲外鍵z.ix你可能會寫

update (select y.x, z.mycol 
      from y, z 
      where y.ix = x.ix) 
    set mycol = x;