重新计算自动编号

来源:互联网 发布:心内事无人知的图片 编辑:程序博客网 时间:2024/06/02 21:44

/*删除数据后,让自动编号ID从1算起有两种方法.
 1为truncate table tbname,它将表中数据全删除的同时,ID也全部清空从1开始.
 2为不带条件的将表中数据删除后,再用dbcc checkident('tbname',noreseed|reseed,newID)清空ID.其中tbname为表名,reseed为更正当前ID值,newID为当前最大标识值
*/
if exists(select name from sysobjects where xtype='U' and name='test')
drop table test
go

create table test(
 ta int identity(1,1),
 tb varchar(10),
        tc varchar(10)
)
go

insert into test
select 'a','aa' union
select 'b','bb' union
select 'c','cc' union
select 'd','dd' 
go

select * from test
go
-------------------------------
1      a      aa
2      b      bb
3      c      cc
4      d      dd

-------------------------------
truncate table test
go

select * from test
go
/*
-------------------------------
(所影响的行数为 0 行)
-------------------------------
*/

-----再次插入值:
insert into test
select 'a','aa' union
select 'b','bb' union
select 'c','cc' union
select 'd','dd' 
go

select * from test
go

/*
-------------------------------
1      a      aa
2      b      bb
3      c      cc
4      d      dd

-------------------------------
ID仍从1起
*/

-----方法2:用dbcc checkident:
delete test
dbcc checkident('test',reseed,0)

-----再次插入值后查看结果与方法1一样.

-----其实dbcc checkident功能是自定义ID值. 如想要下一个ID值从100算起,则将其第三个参数改为99,如想要下一个ID值从4算起,则可按如下方法做,
dbcc checkident('test',reseed,3)

insert into test
select 'a','aa' union
select 'b','bb' union
select 'c','cc' union
select 'd','dd' 
go

select * from test
go

/*
-------------------------------
1    a      aa
2    b      bb
3    c      cc
4    d      dd
4    a      aa
5    b      bb
6    c      cc
7    d      dd
-------------------------------
*/

-----用该方法还可查看最大ID值:
dbcc checkident('test',noreseed)

/*输出结果:
检查标识信息: 当前标识值 '7',当前列值 '7'。
DBCC 执行完毕。如果 DBCC 输出了错误信息,请与系统管理员联系。
*/

***注意:方法1truncate table删除数据不会记录在日志中,删除时速度将全比delete tbname快,但如果有删除触发器,将不会被触发.