Question

Possible Duplicate:
Oracle: Updating a table column using ROWNUM in conjunction with ORDER BY clause

I have a query that returns an ordered set of records, and i want to copy the rownumber of each row in the result set into a particular field called Sequence on the record itself.

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

I have the ID of each row, and the rownum I want to put in the SEQUENCE field. How can I loop through this result set and update the table accordingly?

Was it helpful?

Solution

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

If id is not unique, you can, for sure:

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

OTHER TIPS

Please try:

  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;

which works for unique IDs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top