The output of the SELECT statement will be as follows:
ID Name
------ --------------
1 Bentley
2 BMW
3 Ferrari
4 Lamborghini
5 Hummer
6 Jaguar
7 Lexus
8 Mercedes Benz
9 Porsche
10 Volvo
Let's say certain records have been deleted from the table, as shown in the
following script:
-- Step #2: Delete IDs
DELETE FROM #CarType WHERE [ID] IN (3, 4, 9)
SELECT * FROM #CarType
The table now has the following records:
ID Name
------ --------------
1 Bentley
2 BMW
5 Hummer
6 Jaguar
7 Lexus
8 Mercedes Benz
10 Volvo
One way to identify the missing/deleted identity values is to loop through the
table starting from 1 up to the maximum identity value as shown in the
following script:
-- Step #3 (Option #1): Identify Missing IDENTITY Values
DECLARE @ID INT
DECLARE @MaxID INT
DECLARE @MissingCarTypeIDs TABLE ( [ID] INT )
SELECT @MaxID = [ID] FROM #CarType
SET @ID = 1
WHILE @ID <= @MaxID
BEGIN
IF NOT EXISTS (SELECT 'X' FROM #CarType
WHERE [ID] = @ID)
INSERT INTO @MissingCarTypeIDs ( [ID] )
VALUES ( @ID )
SET @ID = @ID + 1
END
SELECT * FROM @MissingCarTypeIDs
The missing identity values are temporarily stored in a table variable for later
processing. The output of the SELECT statement above is as follows, which
are the deleted identity values:
ID
------
3
4
9