数据库中某表ID(int)列连续增加的问题

来源:百度知道 编辑:UC知道 时间:2024/05/23 15:14:23
问一个小问题:在数据库中有个表的第一列ID怎么样保证从1,2,3。。。连续的增长,在设为自动增长时,一旦删除了其中的一条,就不连续了
不用增量也可以,那怎样保证连续呢?

没办法

你只有先取消标识规范再插数据 然后在恢复表示规范 除此之外别无他法
这样可以保证增量在你查数据的时候不改变
但是在大的数据量情况下不推荐使用标识自增 因为他不好回收数据 就像你遇到的问题一样 插入了3条数据 删除3 他直接从四开始 而且又不能改
所以建议实际应用中少用标识

set nocount on

create table #IDtable
(
id int not null primary key ,
[name] varchar(20) not null
)

insert #IDtable
select 1 ,'a' union
select 2 ,'b' union
select 3 ,'c' union
select 4 ,'d' union
select 5 ,'e' union
select 6 ,'f' union
select 7 ,'g' union
select 8 ,'e'

select * from #IDtable
go

if exists(select * from sysobjects where name='proc_ByID')
drop proc proc_ByID

go

create proc proc_ByID
(
@ID int
)
as

set nocount on

delete from #IDtable where id= @ID

update #IDtable set id =id -1 where id > @ID

go

exec proc_ByI