All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
重新计算自动编号_[SQL,Server教程]

Writer: 归海一刀 Article type: Programming skills(编程技巧) Time: 2014/2/1 0:24:44 Browse times: 622 Comment times: 0

重新计算自动编号_[SQL,Server教程]


Head photo

Go homepage
Upload pictures
Write articles

重新计算自动编号_[SQL Server教程] *删除数据后,让自动编号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快,但如果有删除触发器,将不会被触发.





There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.