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
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
Do you have lots of tables which do not have a seed and increment of 1 ??
If not (by default, all tables have that), use this code:
exec sp_MSforeachtable @command1 = 'DBCC CHECKIDENT(''?'', RESEED, 1)'
MSforeachtable
is an undocumented, but extremely handy stored proc which executes a given command against all tables in your database.
If you need to be absolutely exact, use this statement - it will generate a list of SQL statements to reseed all tables to their original SEED value:
SELECT
IDENT_SEED(TABLE_NAME) AS Seed,
IDENT_INCR(TABLE_NAME) AS Increment,
IDENT_CURRENT(TABLE_NAME) AS Current_Identity,
TABLE_NAME,
'DBCC CHECKIDENT(' + TABLE_NAME + ', RESEED, ' + CAST(IDENT_SEED(TABLE_NAME) AS VARCHAR(10)) + ')'
FROM
INFORMATION_SCHEMA.TABLES
WHERE
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1
AND TABLE_TYPE = 'BASE TABLE'
Grab that last column in the output, and execute those statements and you're done! :-)
(inspired by a blog post by Pinal Dave)
An easy metod may be to use the sp_MSforeachtable command, an undocumented, but relatively well know command that looks over your tables.