Technical Article

Script to List Missing Identity Numbers

,

I have a table named employees with an identity column named id. Also,
last_name is a column in the table named employees. I created the employees
table and inserted 9 rows in it. If I do a select * from employees, the
output looks like this:

id last_name
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i

Then I deleted rows where the id was 3, 4, 6, 7, and 8. So, if I do a
select * from employees, the output looks like this:

id last_name
1 a
2 b
5 e
9 i

So, my missing identity numbers are: 3, 4, 6, 7, and 8.

The code (that I just wrote) below prints to the screen these missing
identity numbers. If you can improve on it or have a better script, let me
know. Thanks.

--Code to Find Missing Identity Values
USE MyDb2
GO
DECLARE @table_name char(9)
SET @table_name = 'employees'
DECLARE @min_id int, @max_id int, @incr_id int
SET @min_id = (SELECT MIN(id) FROM employees)
SET @max_id = (SELECT MAX(id) FROM employees)
SET @incr_id = (SELECT IDENT_INCR(TABLE_NAME)
                 FROM INFORMATION_SCHEMA.TABLES
                 WHERE IDENT_INCR(TABLE_NAME) IS NOT NULL
                 AND TABLE_NAME = @table_name)
CREATE TABLE #u(id INT)
 WHILE (@min_id < @max_id)
   BEGIN
      INSERT INTO #u values (@min_id)
      SET @min_id = @min_id + @incr_id
   CONTINUE
   END
GO
CREATE TABLE #t(id INT )
  INSERT INTO #t
    SELECT id FROM employees
GO
SELECT 'Missing Identity Numbers' 
GO
SELECT DISTINCT id
  FROM #u
    WHERE id NOT IN
     (SELECT id FROM #t)

--select * from #t where id is not null
--select * from #u where id is not null

--DROP TABLE #t
--DROP TABLE #u

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating