2014-04-08 78 views
0

有什麼錯我的如下聲明:Oracle的SQL相關子查詢不起作用

UPDATE TableToUpdate SET ColumnToUpdate = (
    SELECT ColumnWithNewValues 
    FROM (
     SELECT ColumnWithNewValues, ROWNUM AS N 
     FROM Table1 t1, Table2 t2  -- join tables 
     WHERE t2.Schluessel = t1.Schluessel -- join condition 
     AND t1.DateFrom <= TableToUpdate.Date -- <==== Error, reference to TableToUpdate 
     AND t1.DatumTo >= TableToUpdate.Date 
     -- ... some other conditions, not important here ... 
    ) tmp 
    WHERE tmp.N = 5   -- Use the fifth row to update the row of TableToUpdate 
) 

在此執行,我會從Oracle得到一個錯誤:

ORA-00904: "TableToUpdate"."Date": Ungültiger Bezeichner 

在英文我認爲這將意味着:

ORA-00904: "TableToUpdate"."Date": Invalid identifier 

所以看來我不能引用TableToUpdate從一個相關的subquer y在SELECT語句中。在MSSQL下這個工作,當然用 代替oracle特定的ROWNUM當然是一個等價的技術。

有人可以幫助我嗎?

回答

0

您指的是從子查詢中深入兩層,到最外層的表。限制是你只能引用一個級別。因此錯誤信息。

您可以通過將您的更新語句重寫爲合併語句來規避此限制。例如,未經測試,如下所示:

merge into tabletoupdate t 
using (select datefrom 
      , datumto 
      , ColumnWithNewValues 
      from (select t1.datefrom 
         , t1.datumto 
         , ColumnWithNewValues 
         , rownum as n 
        from table1 t1 
         inner join table2 t2 on (t2.Schluessel = t1.Schluessel) -- join condition 
       --where ... some other conditions, not important here ... 
       --order by ... some columns here, otherwise rownum is meaningless 
       ) tmp 
     where tmp.n =5   -- Use the fifth row to update the row of TableToUpdate 
    ) 
    on ( t1.DateFrom <= t.Date 
     and t1.DatumTo >= t.Date 
    ) 
when matched then 
     update set t.columntoupdate = tmp.columnwithnewvalues