一个采用“游标”的经典示例

有人总说游标使用起来比较耗资源,但有些时候通过合理的算法,使用的游标能起到事半功倍的效果

有一个表如下:
CREATE TABLE [#tmp](px int IDENTITY(1,1),value int)
大约有10000条记录,value 字段是一个随机的值,现要求是输入的一个值M,要找出前N条记录,且N条记录value的总和刚好不大M(意思是再多一条记录都会大于M)。

要求:语句运行时间要求在1秒种内完成

说明:
px值小的认为是排在px大的前面

Exa1

select a.* from tmp a where (select sum(value1) from tmp where px<=a.px)<=120

declare @i int,
@num int
set @i=20001
set @num=100000
while @i<@num
begin 
insert into tmp (px,value1)values(@i,@i)
set @i=@i+1
end

select count(*from tmp


Exa2


declare @px int,@s bigint,@m int
set @s=0
set @m=20

update a
set
    
@px=case when @s<=@m then px else @px end,
    
@s =@s+value1
from
    tmp a

select * from tmp where px<@px order by px


--insert into tmp (px,value1)values(1,1)


Exa3

declare @px int,@value int,@sum int,@m int,@px1 int
set @sum=0
set @m=20

declare t_cursor cursor for select px,value1 from tmp order by px

open t_cursor
fetch next from t_cursor into @px,@value

while @@fetch_status=0
begin
    
if(@sum>@m)
        
break
    
set @sum=@sum+@value
    
set @px1=@px
    
fetch next from t_cursor into @px,@value
end
close t_cursor
deallocate t_cursor

select * from tmp where px<@px1 order by px


posted @ 2007-07-19 10:56  憋大招的cat  阅读(280)  评论(0)    收藏  举报