日期:2014-05-18  浏览次数:20533 次

top 问题
declare   @a   int
declare   @b   int
set   @a   =   1
set   @b   =   3
while   @b <   (select   count(*)   from   tablea)
begin  
if   @a   =   1
select   top   @b-@a+1   *     from   tablea
else
select   top   @b-@a+1   *     from   tablea   where   ID   not   in   (select   top   @a-1   ID   from   tablea)
set   @a   =   @a*2
set   @b   =   @b*2
end
不能执行,要怎么改???

------解决方案--------------------
declare @a int
declare @b int

declare @top1 int @top2 int

set @a = 1
set @b = 3
while @b < (select count(*) from tablea)
begin
if @a = 1
set @top1=@b-@a+1
exec ( 'select top '+@top1+ ' * from tablea ')
else
set @top1=@b-@a+1
set @top2=@a-1
exec ( 'select top '+@top1+ ' * from tablea where ID not in (select top '+@top2+ ' ID from tablea) ')
set @a = @a*2
set @b = @b*2
end
------解决方案--------------------
declare @a int
declare @b int
set @a = 1
set @b = 3
declare @sql varchar(1000)
while @b < (select count(*) from tablea)
begin
if @a = 1
set @sql= 'select top ' + rtrim(@b-@a+1) + ' * from tablea '
else
set @sql= 'select top ' + rtrim(@b-@a+1) + ' * from tablea where ID not in (select top '+ rtrim(@a-1)+ ' ID from tablea) '
exec(@sql)
set @a = @a*2
set @b = @b*2
end
------解决方案--------------------
楼上正解!!
------解决方案--------------------
select top @b-@a+1 * from tablea
改为
select top (@b-@a+1) * from tablea
用括号括起来 就可以了