SQL Server Reset Identity Increment for all tables

前端 未结 9 1526
面向向阳花
面向向阳花 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:23

    Another way of using sp_MSForEachTable and checking whether or not the Table has an identity value before resetting it:

    EXEC sp_MSForEachTable '
     Print ''?''
     IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
      DBCC CHECKIDENT (''?'', RESEED, 0)
     else
      Print ''Table does not have an identity value''
    '
    

    NOTE: If you want the identity value to start at 1 then the DBCC command should use CHECKIDENT (''?'', RESEED, 0) not CHECKIDENT (''?'', RESEED, 1) as indicated in some of the answers. Quote from MS SQL Server documentation:

    The following example forces the current identity value in the AddressTypeID column in the AddressType table to a value of 10. Because the table has existing rows, the next row inserted will use 11 as the value, that is, the new current increment value defined for the column value plus 1

    USE AdventureWorks2012;
    GO
    DBCC CHECKIDENT ('Person.AddressType', RESEED, 10);
    GO
    

提交回复
热议问题