Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Identity gap

Author  Topic 

noamg
Posting Yak Master

215 Posts

Posted - 2007-06-07 : 03:29:23
I need to find the gap-range of an integer columns
for example:

create table Nums( num int )
insert into Nums select 1
insert into Nums select 2
insert into Nums select 4
insert into Nums select 7
insert into Nums select 8

the result: fromNum toNum
3, 3
5, 6

thanks


Noam Graizer

mwjdavidson
Aged Yak Warrior

735 Posts

Posted - 2007-06-07 : 04:24:02
Try this:
--Create table variable
DECLARE @gaps TABLE(id INT)

--Insert test data
INSERT INTO @gaps
SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 4
UNION ALL SELECT 5
UNION ALL SELECT 8
UNION ALL SELECT 9

SELECT gap_start.id + 1 AS FromNum,
MIN(gap_end.id) -1 AS ToNum
FROM ( SELECT g1.id
FROM @gaps AS g1
WHERE NOT EXISTS (SELECT * FROM @gaps AS g2 WHERE g2.id = g1.id + 1)
) AS gap_start
JOIN (
SELECT g1.id
FROM @gaps AS g1
WHERE NOT EXISTS (SELECT * FROM @gaps AS g2 WHERE g2.id = g1.id - 1)
) AS gap_end
ON gap_start.id < gap_end.id
GROUP BY gap_start.id


Mark
Go to Top of Page

noamg
Posting Yak Master

215 Posts

Posted - 2007-06-07 : 04:34:46
many thanks !


Noam Graizer
Go to Top of Page

mwjdavidson
Aged Yak Warrior

735 Posts

Posted - 2007-06-07 : 04:57:15
No problem

Mark
Go to Top of Page
   

- Advertisement -