【问题标题】:Oracle-SQL Correlated Subquery in UPDATE-Statement doesn't workUPDATE 语句中的 Oracle-SQL 相关子查询不起作用
【发布时间】:2014-04-08 11:08:07
【问题描述】:

我的以下陈述有什么问题:

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

因此,我似乎无法从 SELECT 语句中的相关子查询中引用 TableToUpdate。在 MSSQL 下,这在将 oracle 特定的 ROWNUM 替换为 当然是等效的技术。

有人可以帮我吗?

【问题讨论】:

    标签: sql oracle select sql-update correlated-subquery


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多