Thursday, 6 March 2014

SQL SERVER - Reseed Identity of Table - Table Missing Identity Values - Gap in Identity Column :

SQL SERVER - Reseed Identity of Table - Table Missing Identity Values - Gap in Identity Column :

Some time ago I was helping one of my Junior Developers who presented me with an interesting situation. He had a table with Identity Column. Because of some reasons he was compelled to delete few rows from the table. On inserting new rows in the table he noticed that the rows started from the next identity value which created gap in the identity value. His application required all the identities to be in sequence, so this was certainly not a small issue for him.

The solution to this issue regarding gap in identity column is very simple. Let us first take a look at his application’s situation wherein there is missing identity and then we will move on to the solution.
Developers can easily deter the above issue by avoiding gap in sequence of identity column through two additional SQL Tricks of reseeding identity.
We will now see the same example with the solution to the above gap issue. On deleting records, table was reseeded with identity, which was deleted. Download complete SQL Script here.
USE AdventureWorks
GO
/* Create a table with one identity column */CREATE TABLE TableID (ID INT IDENTITY(1,1), Col VARCHAR(10))GO/* Insert 10 records with first value */INSERT INTO TableID (Col)VALUES ('First')GO 10/* Check the records in table */SELECT *FROM TableID
GO
/* Delete last few records */DELETE
FROM 
TableIDWHERE ID IN (8,9,10)GO/* Check the records in table */SELECT *FROM TableID
GO
/* Get current Max Value and reseed table */DECLARE @MaxID INT
SELECT 
@MaxID = MAX(ID)FROM TableIDDBCC CHECKIDENT('TableID'RESEED@MaxID)GO/* Insert 10 records with second value */INSERT INTO TableID (Col)VALUES ('Second')GO 5/* Check the records in table */SELECT *FROM TableID
GO
/* Clean Database */DROP TABLE TableID
GO