Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reseed sql server identity columns

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)

like image 475
user194076 Avatar asked Jun 30 '11 23:06

user194076


People also ask

Can we reset identity column in SQL Server?

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.

Does IDENTITY insert reseed?

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.

How do I reseed a table in SQL Server?

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.


2 Answers

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;
like image 113
Aaron Bertrand Avatar answered Sep 22 '22 00:09

Aaron Bertrand


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.

like image 22
Alex Hinton Avatar answered Sep 21 '22 00:09

Alex Hinton