1

可能重复:
Oracle:使用 ROWNUM 和 ORDER BY 子句更新表列

我有一个返回有序记录集的查询,我想将结果集中每一行的行号复制到记录本身上称为序列的特定字段中。

SELECT ROWNUM, ID
FROM (
    SELECT ID 
    FROM MYTABLE 
    WHERE PARENT = 1
    ORDER BY SEQUENCE ASC
)

我有每一行的 ID,并且rownum我想在SEQUENCE字段中输入。如何循环遍历此结果集并相应地更新表?

4

2 回答 2

2
merge into mytable t
using (SELECT ROWNUM rn, ID
       FROM (
         SELECT ID 
         FROM MYTABLE 
         WHERE PARENT = 1
         ORDER BY SEQUENCE ASC
      )) S 
on (t.id=s.id)
when matched then update set
  t.sequence=s.rn

如果 id 不是唯一的,您可以肯定:

merge into mytable t
using (SELECT ROWNUM rn, rwd
       FROM (
         SELECT rowid rwd
         FROM MYTABLE 
         WHERE PARENT = 1
         ORDER BY SEQUENCE ASC
      )) S 
on (t.rowid=s.rwd)
when matched then update set
  t.sequence=s.rn
于 2013-01-31T12:42:50.860 回答
1

请试试:

  merge into EMP_MASTER x
  using (
          SELECT ID, ROW_NUMBER() OVER(ORDER BY SEQUENCE) y
          FROM MYTABLE 
          WHERE PARENT = 1
         ) s on (s.ID=x.ID)
         when matched then update set
  x.sequence=s.y;

这适用于唯一 ID。

于 2013-01-31T12:45:11.540 回答