Oracle update query to update records in sequential order

二次信任 提交于 2019-12-20 07:38:45

问题


I have a table in Oracle SQL whose ids are in increasing, sequential order, but there are gaps in the ids due to editing, e.g. the ids are currently something like

22 
23 
24 
32 
33 
44 
...etc

I check one post and the solution provided was as below:

update (select t.*, row_number() over (order by id) as newid) toupdate
    set id = newid

Solution Provided earlier.

Now my query: 1) I guess the "From clause" is missing in the above query.

Updated query:

update (select t.*, 
              row_number() over (order by emp_id) as newid 
       from employee t ) toupdate 
set emp_id = newid; 

2) When i run the above query, it gives me error "data Manipulation operation not legal on this view".

Can anyone explain how the mentioned solutions worked here. can anyone post the full update query. Thanks.


回答1:


This solution to the same question you referenced shows how to do it:

update employee set emp_id = (
  with tab as (
    select emp_id, rownum r
    from   (select emp_id from employee order by emp_id)
  )
  select r from tab where employee.emp_id = tab.emp_id
);

That works. You cannot update a view that contains an analytic function like row_number - see Oracle 12C docs, look for "Notes on Updatable Views".




回答2:


You could use a merge, but you'd need to join on something other than emp_id as you want to update that column. If there are no other unique columns you can use the rowid:

merge into employee target
using (select rowid, row_number() over (order by emp_id) as emp_id from employee) source
on (source.rowid = target.rowid)
when matched then update set target.emp_id = source.emp_id;



回答3:


I think this would be easiest approach :

update mytable set id = ROWNUM;

Oracle SQL - update ids in oracle sql to be in sequential order



来源:https://stackoverflow.com/questions/38789481/oracle-update-query-to-update-records-in-sequential-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!