利用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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM