SQL数据库表自增列重新排列

来源:互联网 发布:javascript百度云盘 编辑:程序博客网 时间:2024/06/07 12:19

将Customer替换为自己的表

ID为自增字段

 

使用SQLServer的自增功能来管理表的关键字,时间久后由于删除原因ID会不连续,如何重新“整理”关键字ID,使其重新从1开始,并且重置自增初始值为当前记录个数?


exec sp_configure 'allow updates',1
reconfigure with override
GO


update syscolumns set colstat = 0 where id =object_id('dbo.Customer') and colstat = 1
GO


update  dbo.Customer 
set  ID=(select  count(1)  from  dbo.Customer  where  ID<=t.ID)   
from  dbo.Customer   t
GO


declare @a int 
set @a=(select count(*) from dbo.Customer)


DBCC CHECKIDENT (Customer, RESEED, @a)
GO


update syscolumns set colstat = 1 where id =object_id('dbo.Customer') and name = 'ID'
GO  


exec sp_configure 'allow updates',0
reconfigure with override