我有一个这样的 Oracle 表:
fruit id
-------- -----
apple 1
plum 9
pear 55
orange 104
..
id 列号错误。如何更新每行的 id 以重新排序,如下所示:
fruit id
-------- -----
apple 1
plum 2
pear 3
orange 4
最有效的方法是什么?
update your_table
set id = rownum
如果您需要保证旧订单,则应执行以下操作:
merge into the_table
using
(
select rowid as rid,
row_number() over (order by id asc) as new_id
from the_table
) t on (t.rid = the_table.rowid)
when matched then
update set id = new_id;
DECLARE
i INTEGER :=1;
BEGIN;
FOR n IN (SELECT your_primary_id FROM your_table_name ORDER BY your_primary_id);
LOOP;
UPDATE your_table_name
SET your_primary_id=i
WHERE your_primary_id = n.your_primary_id;
i := i + 1;
END LOOP;
END;
/