DBCC CHECKIDENT RESEED — is new value required?

给你一囗甜甜゛ 提交于 2019-12-01 04:05:28

As it is stated in MSDN, it is fairly enough to use just:

 DBCC CHECKIDENT('tablename', RESEED)  

most of the time, however there are these two conditions where it will not work:

  • The current identity value is larger than the maximum value in the table.
  • All rows are deleted from the table.

in which you have to go with they way that you mentioned (select max(id) and the rest), so why bother in the first place? :)

There are cases where you might want to determine the max so that you can reseed and leave a gap (e.g. max + 100). One case might be when you have multiple copies of a table and you are going to distribute independent but mutually exclusive identity ranges from them.

But still, I'm not confident that the RESEED without a parameter will work correctly in all scenarios.

Is it a common occurrence that you're reseeding tables back to the max? Why? Poorly coded application that generates a bunch of rows in a loop that you end up rolling back?

In any case, you'll want to wrap the MAX and RESEED in a transaction to prevent the chance that a user will insert a new row after you've taken the max but before you've issued the reseed.

010110110101

(I'm reposting my answer from this other SO page)

Perhaps the easiest way (as crazy as this sounds and as code-smelly as it looks) is to just run DBCC CHECKIDENT twice like this:

-- sets all the seeds to 1
exec sp_MSforeachtable @command1 = 'DBCC CHECKIDENT (''?'', RESEED, 1)'

-- run it again to get MSSQL to figure out the MAX/NEXT seed automatically
exec sp_MSforeachtable @command1 = 'DBCC CHECKIDENT (''?'')'

Done.

If you want, you can run it once more to see what all the seeds were set to:

-- run it again to display what the seeds are now set to
exec sp_MSforeachtable @command1 = 'DBCC CHECKIDENT (''?'')'

This is just a creative way to take advantage of the comment from the documentation:

If the current identity value for a table is less than the maximum identity value stored in the identity column, it is reset using the maximum value in the identity column.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!