寻找黑洞

        做一回标题党!这不是一个探索宇宙的问题,实际问题如下:

        某表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

 

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值