如何在没有主键的情况下使用 table 上的连续更新 table?

How to update table with sequentional on table without primary key?

在 Linux v11.1 上的 DB2 中,我有一个 table:

COL1   COL2  "COLn 50 more columns"
A      A
A      A
B      A
B      B
etc 3 million rows

可以有多行具有相同的行,就像我示例中的前两行(很明显 table 上没有主键)。

现在我必须添加新的列 ID 并为每一行设置唯一的序号。 结果应该是:

COL1   COL2  "COLn 50 more columns"   ID
A      A                               1
A      A                               2
B      A                               3
B      B                               4
etc 3 million rows

如何写这样一条更新ID列的更新语句? 此致

这是一种方法,使用 identity column ,它假定不存在现有的主键或标识列。

alter table myschema.mytab add column id integer not null default 0 ;

alter table myschema.mytab alter column id drop default ;


alter table myschema.mytab alter column id set generated always as identity ;


update myschema.mytab set id = default ;

-- optional, if you want the new ID column to be a surrogate primary key

alter table myschema.mytab add constraint pkey primary key(id) ;

reorg table myschema.mytab ;

runstats on table myschema.mytab with distribution and detailed indexes all;

试试这个:

alter table myschema.mytab add column id integer not null default 0 ;

UPDATE (SELECT ID, ROWNUMBER() OVER() RN FROM myschema.mytab) SET ID = RN;
-- Or even simplier:
-- UPDATE myschema.mytab SET ID = ROWNUMBER() OVER();