日期:2014-05-19  浏览次数:20413 次

分页问题

这是分页的sql语句:

select   top   10   *   from   表   where   回复   is   not   null   and   (id   not   in   (select   top   (当前页-1)*10     *   from   表))
----------------------------
为什么结果不能正常显示呢?


------解决方案--------------------
(当前页-1)*10 不能这样用的,要用动态SQL
declare @sql nvarchar(4000)
declare @i int --当前页
set @i=1
select @sql=N 'select top 10 * from 表 where 回复 is not null and (id not in (select top '+ Convert(nvarchar(10),(@i -1)*10 )+N ' id from 表)) '
print @sql
EXEC(@sql)

另外括号里面应该选出来ID 而不是*


------解决方案--------------------
create table feia
(
a1 char(6) not null PRIMARY KEY,
a2 datetime ,
a3 varchar(10) ,
a4 varchar(10)
)

declare @sql nvarchar(4000)
declare @i int --当前页
set @i=1
select @sql=N 'select top 3 * from feia where (a1 not in (select top '+ Convert(nvarchar(10),(@i -1)*3 )+N ' a1 from feia group by a1)) '
print @sql
EXEC(@sql)


insert into feia
select '001201 ', '2007-06-03 ', '进货单1 ', '王三 '
union all
select '001211 ', '2007-06-03 ', '进货单2 ', '张三 '
union all
select '001231 ', '2007-06-01 ', '进货单3 ', '王三 '
union all
select '001241 ', '2007-07-09 ', '进货单4 ', '谷三 '