Similar to MySql I want update (fill) an empty column with incremental values -- with Oracle . Ie after
ALTER TABLE data ADD
(
id number
);
I want for all records the ID
column to receive unique values. After that I will enable Not Null and unique constraints to make it a primary key .
I came up quickly with
UPDATE TABLE data SET id = rownum;
but I have a bad feeling about this. It works in my tests as expected, but an example is no proof :-)
Is it safe to use rownum
in this manner in an update
-statement?
是的,我从未遇到过这种方法的问题,但是启用非null和唯一约束不会使它成为主键-添加主键约束使其成为主键;)
Probably, your method is safe. If not, you would be notified if unique constraint fails :-).
Bullet-proof method is the following:
lock table data in exclusive mode;
merge into data t
using (select t.rowid rid, t.rownum id from data t) s
on (t.rowid = s.rid)
when matched then update set
t.id = s.id;
commit;
No, it is not safe, as ROWNUM is pseudocolumn. Means it does not guarantee the sequence especially when using with ORDER BY. If you must, then use ROW_NUMBER() OVER (ORDER BY your_field) instead of ROWNUM. You may also use PL/SQL to update your table once in the loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.