Question : Find Missing IDENTITY Values in SQL Server 2005 / 2008

Hi,

I have the following table (T)

-- Create a table

CREATE TABLE T
(
    id          int    INDENTITY (1, 1),
    Name   varchar(50)
)

Here is the data i have in that table (T):

1               Steve
2               Jack
3               Ram
5               Eric
7               Munna

I have the missing id's existing in the data - 4 and 6. Can you please provide me an SQL query to find the missing identity (id) values ? Please remember to explain the SQL query !

Thanks

Answer : Find Missing IDENTITY Values in SQL Server 2005 / 2008

@Ernariash: seems very familiar to a different thread - new trick i guess...

As a once off exercise and depending on number of rows, the CTE query is the way to go here...

basically creating a dynamic list of numbers which you then check against the ID's

the cte is good here because it essentially creates the list of all possible ID's, by simply adding one to itself - we simply start at 1 and could be any starting point - and we stop at maxid which is initially set to be the highest ID currently used.







1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
WITH numbers (NUM, maxid)
AS 
( 
 SELECT 1 AS num, (select max(id) from tableT) 
 UNION ALL 
 SELECT num + 1, maxid FROM numbers  
 WHERE num < maxid
) 
SELECT num 
FROM numbers  
left outer join tableT on tableT.id = numbers.num
where tablet.id is NULL
OPTION (MAXRECURSION 0); 
Open in New Window Select All
Random Solutions  
 
programming4us programming4us