做一回标题党!这不是一个探索宇宙的问题,实际问题如下:
某表base_table,千万数据级别,其中ID列为数字,从1开始。请找出该列中的不连续数字。
我给出的大体思路是先构建一个初始为1~10000的序列表,然后循环步进关联基础表进行筛选。代码如下:
declare @begin_on datetime
--记录开始时间
select @begin_on = getdate();
declare @max_id int, @times int, @step int, @index int
select @step = 10000; --步进大小
select @index = 0; --循环初始值
select @max_id = max(id) from base_table; --原始表中最大数据
select @times = ceiling(@max_id / @step); --每次步进@step的循环次数
set nocount on
--序列表,保存一个基础序列。
create table #temp_seq
(
id int identity(1, 1),
col int
)
--目标表,记录遗失的数字
create table #temp_missed
(
id int
);
--创建原始序列。序列大小为@step
insert into #temp_seq select top(@step) id from base_table with (nolock) ;
--循环查找,每次步进@step
while(@index < @times)
begin
insert into #temp_missed
select a.id + (@index * @step) from #temp_seq a with (nolock) where
not exists(select * from base_table b with (nolock)
where a.id + (@index * @step)=b.id)
and a.id + (@index * @step) <= @max_id;
select @index = @index + 1;
end
--统计花费时间
select datediff(ms, @begin_on, getdate())
select * from #temp_missed
drop table #temp_seq
drop table #temp_missed
set nocount off