当前位置: 代码迷 >> Sql Server >> top 有关问题
  详细解决方案

top 有关问题

热度:85   发布时间:2016-04-27 19:40:24.0
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   @[email protected]+1   *     from   tablea
else
select   top   @[email protected]+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 '[email protected]+ ' * from tablea ')
else
set @top1=@b-@a+1
set @[email protected]
exec ( 'select top '[email protected]+ ' * from tablea where ID not in (select top '[email protected]+ ' 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(@[email protected]+1) + ' * from tablea '
else
set @sql= 'select top ' + rtrim(@[email protected]+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 @[email protected]+1 * from tablea
改为
select top (@[email protected]+1) * from tablea
用括号括起来 就可以了
  相关解决方案