在 table 中添加列后插入唯一值

Insert unique values after addition of a column in a table

我们有一个包含两列的 table 并且最近添加了另一列(名为 sequence_no),有没有办法为中的每一行插入唯一值,例如 1,2,3 table ?

例如

table name :   test
desc test
name varchar2
value varchar2
--> n_seq_no number

select * from test
Name    value   n_Seq_no
test1      100
test2      200
test3      300
test4      500

table 已有名称和值作为 table 的列,我需要使用现有数据为 n_Seq_no 列添加唯一值,

输出格式:

select * from test
Name    value   n_Seq_no
test1      100   1
test2      200   2
test3      300   3
test4      500   4 

等等 table.

中的所有行

您可以简单地将新列设置为 ROWNUM

有点像,

SQL> CREATE TABLE t(
  2  A NUMBER,
  3  b NUMBER);

Table created.

SQL>
SQL> INSERT INTO t(A) VALUES(100);

1 row created.

SQL> INSERT INTO t(A) VALUES(200);

1 row created.

SQL> INSERT INTO t(A) VALUES(300);

1 row created.

SQL>
SQL> SELECT * FROM t;

         A          B
---------- ----------
       100
       200
       300

SQL>
SQL> UPDATE t SET b = ROWNUM;

3 rows updated.

SQL> SELECT * FROM T;

         A          B
---------- ----------
       100          1
       200          2
       300          3

SQL>

如果您使用 12c,您可以使用 IDENTITY COLUMN.

假设您的 table 确实很大,最好重新创建和重新填充:

rename test to old_test;

create table new_test
as
select t.*, rownum as n_seq_no 
  from old_test t
 order by value;

不要忘记迁移授权、索引、触发器等(如果有的话)。

更新:订购是可选的。仅当您想使用一些预定义的顺序分配 n_seq_no 值时才需要它。