Коррелированный подзапрос Oracle-SQL в операторе UPDATE не работает

что не так с моим следующим утверждением:

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
)

При выполнении этого я получу ошибку от оракула:

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

По-английски, я думаю, это будет означать:

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

Итак, кажется, что я не могу ссылаться на TableToUpdate из коррелированного подзапроса в операторе SELECT. В MSSQL это работает при замене ROWNUM, специфичного для оракула, на эквивалентную технологию, конечно.

Кто-нибудь может мне помочь?


person user3214697    schedule 08.04.2014    source источник


Ответы (1)


Вы ссылаетесь изнутри своего подзапроса на два уровня в глубину на самую внешнюю таблицу. Ограничение состоит в том, что вы можете ссылаться только на один уровень вверх. Отсюда и сообщение об ошибке.

Вы можете обойти это ограничение, переписав оператор обновления в оператор слияния. Например, непроверенное, вот так:

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
person Rob van Wijk    schedule 08.04.2014