Question

I seem to remember in MySQL when truncating a table the auto incremented index field would continue where it left off. So if said table was truncated with the highest id was 100, the next id after truncation would be 101.

Is there a way to do this in SQL Server? I truncated my table with over 1000 rows, but after truncating the next new id went back to 1 in my identity column. I would like for it to continue.

Was it helpful?

Solution

DBCC CHECKIDENT (<table name>, reseed, 1000) should do the trick.

Note that the the reseed shown above will mean that the next number will be 1001, so set to 999 if you want the next ID to be 1000.

This article explains a bit more.

OTHER TIPS

Building on the answer from GrandMasterFlush, here is a script I use to achieve this "truncate but retain seed" functionality, assuming your id is bigint.

declare @id bigint
select @id = IDENT_CURRENT('MyTable')
print(@id)
truncate table MyTable
dbcc checkident (MyTable, reseed, @id)

From MSDN:

If the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used. To retain the identity counter, use DELETE instead.

If you are set upon truncating the table, you can manually look up the maximum ID before truncating, and then reseed the table using DBCC CHECKIDENT.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top