DBCC CHECKIDENT RESEED — is new value required?

前端 未结 3 1293
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 10:26

All the documentation I read about reseeding suggests something along the lines of:

  1. SET @maxIdentityValue = (SELECT MAX(id) FROM tablename)
  2. <
3条回答
  •  不思量自难忘°
    2021-01-12 10:48

    (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.

提交回复
热议问题