在db2sql中重置数字顺序

时间:2017-03-20 03:22:00

标签: sql db2

如何重置现有的数据订单号?我试过alter table tb_shk_user alter column autonum restart with 1,它仅适用于新数据插入,数字将从数字1开始,但会与现有数据重复。enter image description here

autonum列属性

AUTONUM INTEGER NOT NULL始终为身份(从1开始增加1)主键

2 个答案:

答案 0 :(得分:0)

或者这个:

--Save data of your table into temporary table   
create table tmptable as 
(
select * from tb_shk_user 
) 
with data;

--Remove all rows into your table
delete from tb_shk_user ;

--Insert into your table all rows with renumber for autonum, be carefull all columns mus be in select except autonum
insert into tb_shk_user overriding system value
select rownumber() over(order by autonum) as newautonum, username, mobilno
from tmptable;


-- Reposition of autoincrement on max + 1
-- Example if 47896 is the max + 1 of autonum after preceding insert 
alter table tb_shk_user alter column autonum restart with 47896;

答案 1 :(得分:0)

我想你想要重启以获得一系列好的id,然后你就可以了。

--Temprary table with key autonum and new num ordered
create table tmptable as (
select autonum, rownumber() over(order by autonum) as newautonum
from tb_shk_user 
) with data;

--Update your table with new num
update tb_shk_user f1 overriding system value
set f1.autonum=
(
select f2.newautonum from tmptable f2
where f1.autonum=f2.autonum
)
where exists 
(
select * from tmptable f2
where f1.autonum=f2.autonum
);

-- Reposition of autoincrement on max + 1
-- Example if 47896 is the max + 1 of autonum after preceding update 
alter table tb_shk_user alter column autonum restart with 47896;