I reseed identity columns like this:
EXEC sp_MSforeachtable "DBCC CHECKIDENT ( '?', RESEED, 0)"
Query throws me an error if there's no identity in the table. But I still need to reseed identity for all tables in the database that have an identity. (And do not throw an error if there's no identity)
Reset the Identity Value Using the DBCC CHECKIDENT Procedure Resetting our produce table to use a value of 1 is done using this command: DBCC CHECKIDENT ('product', RESEED, 0); However, there are existing records in the table, so if we reset it and insert a new record, there will be an error.
Automatic reseeding can occur This happens when you turn on IDENTITY_INSERT for the table, then insert a row with an ID that is higher than the current ID. The IDENTITY seed value will be reset to that higher ID value you outlined.
Execute DBCC CHECKIDENT (table_name, RESEED,new_reseed_value) with new_reseed_value set to a very low value, and then run DBCC CHECKIDENT (table_name, RESEED) to correct the value. All rows are deleted from the table.
Are all the tables really empty?
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql = @sql + N'DBCC CHECKIDENT('''
+ QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))
+ '.' + QUOTENAME(OBJECT_NAME([object_id]))
+ ''', RESEED, 0);' + CHAR(13) + CHAR(10)
FROM sys.columns
WHERE is_identity = 1;
PRINT @sql;
-- EXEC sp_executesql @sql;
To reseed all tables to 0 that have an identity column in one line:
exec sp_MSforeachtable 'dbcc checkident(''?'', reseed, 0)', @whereand='and exists(select 1 from sys.columns c where c.object_id = o.id and is_identity = 1)'
Checking identity information: current identity value '33798', current column value '0'. DBCC execution completed. If DBCC printed error messages, contact your system administrator. Checking identity information: current identity value '3359', current column value '0'. DBCC execution completed. If DBCC printed error messages, contact your system administrator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With