Chodzi o to, aby przyjrzeć się, gdzie zaczynają się luki. Załóżmy, że używasz SQL Server 2012, więc masz lag() i lead() Funkcje. Następujące pobiera następny id :
select t.*, lead(id) over (order by id) as nextid
from t;
Jeśli jest luka, to nextid <> id+1 . Możesz teraz scharakteryzować luki za pomocą where :
select id+1 as FirstMissingId, nextid - 1 as LastMissingId
from (select t.*, lead(id) over (order by id) as nextid
from t
) t
where nextid <> id+1;
EDYCJA:
Bez lead() , zrobiłbym to samo z skorelowanym podzapytaniem:
select id+1 as FirstMissingId, nextid - 1 as LastMissingId
from (select t.*,
(select top 1 id
from t t2
where t2.id > t.id
order by t2.id
) as nextid
from t
) t
where nextid <> id+1;
Zakładając id jest kluczem podstawowym w tabeli (lub nawet ma indeks), obie metody powinny mieć rozsądną wydajność.