Click to See Complete Forum and Search --> : How to find holes in IDENTITY column?
Gatwick
May 16th, 2004, 06:03 AM
I have table with ObjectID column and this column is intidentity. There're 10 000 000 rows in table. Somebody has dropped part of them (about 10000) but have written their IDs nowhere. I need a way to find theese ObjectIDs in a fastest manner so wait for your advises.
hspc
May 16th, 2004, 01:43 PM
assuming the table name is Object and the Identity column is ObjectID
--method 1 simple query
select ObjectID+1 from Object as O
where not exists (select ObjectID from Object where (ObjectID=O.ObjectID+1))
and ObjectID<>(select max(ObjectID) from object)
the bad thing with this way is that it will miss any deleted IDs at the beginning ie: if 1,2,3 are ddeleted you'll not get them
--method 2
declare @prevID int,@ObjID int
declare @MissingTable table (IDs int)
declare delObjCursor cursor FAST_FORWARD
for select ObjectID from object order by ObjectID
Open delObjCursor
fetch next from delObjCursor into @ObjID
set @prevID=0 --assuming Identity_seed is 1
While @@fetch_status=0
begin
set @prevID=@prevID+1
While @prevID<@ObjID
begin
print @prevID
print @ObjID
Insert into @MissingTable values(@prevID)
set @prevID=@prevID+1
End
fetch next from delObjCursor into @ObjID
End
deallocate delObjCursor
select * from @MissingTable
Go
this method will get all holes but it's more complicated and may take more time to execute.
sure there are more ways to do this.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.