日期:2014-05-17  浏览次数:20500 次

自动编号如何修改
在数据库插入了几行数据,现在删掉了一行,发现系统自动编的号也删了,编号不再连续,如何使编号还像以前一样从1开始而且是连续的??我的是sql server 2008的
------解决方案--------------------
/*       自增列的基本操作[為已存在的列按自增值更新]   */   
--表  
 if object_id('t') is not null 
 drop table t   
 go   
 create table t(   id int,   col nvarchar(20)   )   
 go   
 --測試數據   
 insert t 
 select null,'test1'  union all 
 select null,'test2'  union all 
 select null,'test2'  union all 
 select null,'test1'  go   
 --第一種:按指定順序設置id(但只能更新原有数据,設置不了自增,不算)   
 update t       
 set id=t1.rn       
 from (select row_number() over(order by col) rn,col from t)t1       
 where t.col=t1.col;  
go   
select * from t order by col;   
go   
--第二種:根據數據庫實際存儲數據設置自增id  
alter table t drop column id;   
alter table t add id int identity(1,1) not null;  
go   
select * from t;  
go   
--第三種:根據自已設置的順序設置自增id   
if object_id('t_copy') is not null 
drop table t_copy  
select col into t_copy from t order by col;   
truncate table t;  
alter table t drop column id;   
alter table t add id int identity(1,1) not null;   
insert into t(col) select col from t_copy;  
go   
select * from t order by col;  
go  
 --第四種:根據自已設置的順序設置自增id,且保持原列順序   
if object_id('t_copy') is not null 
drop table t_copy   
select col into t_copy from t order by col;              
drop table t;  
select id=identity(int,1,1),col into t from t_copy;              
go   
select * from t order by col;   
go 
/* 如果经常增删数据记录的话,自增ID列没多大意义,可以将ID列设置为uniqueidentifier, 建新列DateTime记录插入时间以便排序
 
------解决方案--------------------
把数据移到一个新表去,然后truncate 源表,再插回去。就可以重新从1开始
------解决方案--------------------
实现麻烦,且没必要这样
------解决方案--------------------
引用:
把数据移到一个新表去,然后truncate 源表,再插回去。就可以重新从1开始

好方法,我怎么没想到
------解决方案--------------------