利用SQL语句重置数据库中所有表的标识列(自增量)

可以应用于2种场景:

1.清空所有表中的数据,数据清空后,最好是能够让表中的标识列从1开始记数,所以要重置标识列的当前值。

2.用复制的方式,发布订阅同步数据之后,订阅端的数据不会自动增长,比如自增ID该9527了,但如果中间有跳过的ID,会自动填充缺失的路过的ID,该执行如下代码,即可从应该的9527开始增长。

declare @tablename varchar(50) 
declare @sql varchar(1000)
declare cur cursor for select name from sys.tables 
open cur
fetch next from cur into @tablename
while @@fetch_status=0
begin
set @sql='if (select count(1) from '+@tablename+')<=0 and exists(select * from sys.columns where is_identity=1 and object_id=object_id('''+@tablename+'''))
begin
--dbcc checkident('+@tablename+',reseed,1)
dbcc checkident('+@tablename+',reseed)
end'
exec (@sql)
fetch next from cur into @tablename 
end 
close cur
deallocate cur

 测试过没有问题的

--已经测试没有问题的生成有标识列(自增ID)的表名
declare @tablename varchar(50) 
declare @sql varchar(1000)
declare @objiecid int
declare cur cursor for select object_id from sys.columns where is_identity=1  
open cur
fetch next from cur into @objiecid
while @@fetch_status=0
begin
select @tablename=name from sys.tables where object_id=@objiecid
--print @tablename
print 'dbcc checkident('''+@tablename+''',reseed)'
fetch next from cur into @objiecid 
end 
close cur
deallocate cur

 

转载于:https://www.cnblogs.com/davidhou/p/4769317.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值