重置SQLSERVER表的自增列,让自增列重新计数

很多时候我们需要重置某个表的自增列,让自增列重新从1开始记数。最蠢的方法当然是把该表删掉再重新建表了。其实,还有其它的方法可以重置自增列的值:


方法一:使用TRUNCATE TABLE语句:
TRUNCATE TABLE删除表中的所有行,而不记录单个行删除操作,同时重置自增列。TRUNCATE TABLE 在功能上与没有WHERE子句的DELETE语句相同;但是,TRUNCATE TABLE 速度更快,使用的系统资源和事务日志资源更少。


方法二:使用DBCC CHECKIDENT语句:
DBCC CHECKIDENT在 SQL Server 2008 R2 中检查指定表的当前标识值,如有必要,则更改标识值。还可以使用 DBCC CHECKIDENT 为标识列手动设置新的当前标识值。


语法:


DBCC CHECKIDENT
(
  table_name
  [, { NORESEED | { RESEED [,new_reseed_value ] } } ]
 )
 [ WITH NO_INFOMSGS ]


参数:
table_name:是要对其当前标识值进行检查的表名。指定的表必须包含标识列。表名必须符合标识符规则。
NORESEED:指定不应更改当前标识值。
RESEED:指定应该更改当前标识值。
new_reseed_value:用作标识列的当前值的新值。
WITH NO_INFOMSGS:取消显示所有信息性消息。


示例:我们要重置表t1的当前标识值为1,sql如下:


dbcc checkident('t1',reseed,1)


我们要查询表t1的当前标识值,sql如下:


dbcc checkident('t1',noreseed)


If you run into the following error message:
An explicit value for the identity column in table ‘<TABLE_NAME>’ can only be specified when a column list is used and IDENTITY_INSERT is ON.
It can mean two things.

One you’ve not enabled identity insert on your table, meaning SQL Server will not let you insert into the Identity column.
This can be rectified with the following statement:
SET IDENTITY_INSERT table_name ON 
And then turn it off again when done
SET IDENTITY_INSERT table_name OFF

However it can also mean that you are using for example INSERT INTO, in which cause the message tells you to specify the column names. This means using the following syntax:

INSERT INTO target_able_name (column_name1column_name2…. column_nameN)
SELECT
YOUR_SELECT_LIST_WHICH_MATCHES_COLUMN_LIST
FROM source_table_name

I wasn’t aware of the latter syntax myself before I got the error message today. But then I learned a little something new today after all :)


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值