2014-04-08 39 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