Reset identity seed after deleting records in SQL

2019-01-01 16:33发布

I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity defined.

But since I have to delete some records from the table, the identity seed for those tables will be disturbed and the index column (which is auto-generated with an increment of 1) will get disturbed.

How can I reset the identity column after I deleted the records so that the column has sequence in ascending numerical order?

The identity column is not used as a foreign key anywhere in database.

17条回答
时光乱了年华
2楼-- · 2019-01-01 17:01

issuing 2 command can do the trick

DBCC CHECKIDENT ('[TestTable]', RESEED,0)
DBCC CHECKIDENT ('[TestTable]', RESEED)

the first reset the identity to zero , and the next will set it to the next available value -- jacob

查看更多
公子世无双
3楼-- · 2019-01-01 17:06

First : Identity Specification Just : "No" >> Save Database Execute Project

After then : Identity Specification Just : "YES" >> Save Database Execute Project

Your Database ID, PK Start from 1 >>

查看更多
人间绝色
4楼-- · 2019-01-01 17:17

@jacob

DBCC CHECKIDENT ('[TestTable]', RESEED,0)
DBCC CHECKIDENT ('[TestTable]', RESEED)

Worked for me, I just had to clear all entries first from the table, then added the above in a trigger point after delete. Now whenever i delete an entry is taken from there.

查看更多
梦寄多情
5楼-- · 2019-01-01 17:17

Run this script to reset the identity column. You will need to make two changes. Replace tableXYZ with whatever table you need to update. Also, the name of the identity column needs dropped from the temp table. This was instantaneous on a table with 35,000 rows & 3 columns. Obviously, backup the table and first try this in a test environment.


select * 
into #temp
From tableXYZ

set identity_insert tableXYZ ON

truncate table tableXYZ

alter table #temp drop column (nameOfIdentityColumn)

set identity_insert tableXYZ OFF

insert into tableXYZ
select * from #temp
查看更多
永恒的永恒
6楼-- · 2019-01-01 17:17
DBCC CHECKIDENT (<TableName>, reseed, 0)

This will set the current identity value to 0.

On inserting the next value, the identity value get incremented to 1.

查看更多
登录 后发表回答