SQL Server Reset Identity Increment for all tables

前端 未结 9 1622
面向向阳花
面向向阳花 2021-01-30 05:38

Basically I need to reset Identity Increment for all tables to its original. Here I tried some code, but it fails.

http://pastebin.com/KSyvtK5b

Actual code from

9条回答
  •  自闭症患者
    2021-01-30 06:19

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

提交回复
热议问题