数据库分页的方法(转)

本文将对实现分页的方式作一些探讨:
方式一:(利用Not In和SELECT TOP分页)
语句形式:
SELECT TOP 页大小 *
FROM TestTable
WHERE (ID NOT IN
          (
SELECT TOP 页大小*页数 id
         
FROM 表
         
ORDER BY id))
ORDER BY ID

方式二:(利用ID大于多少和SELECT TOP分页)
SELECT TOP 页大小 *
FROM TestTable
WHERE (ID >
          (
SELECT MAX(id)
         
FROM (SELECT TOP 页大小*页数 id
                 
FROM 表
                 
ORDER BY id) AS T))
ORDER BY ID

方式三:(利用SQL的游标存储过程分页)
create  procedure XiaoZhengGe
@sqlstr nvarchar(4000), --查询字符串
@currentpage int--第N页
@pagesize int --每页行数
as
set nocount on
declare @P1 int--P1是游标的id
 @rowcount int
exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output
select ceiling(1.0*@rowcount/@pagesizeas 总页数--,@rowcount as 总行数,@currentpage as 当前页 
set @currentpage=(@currentpage-1)*@pagesize+1
exec sp_cursorfetch @P1,16,@currentpage,@pagesize 
exec sp_cursorclose @P1
set nocount off

方式四:AspNetPager的存储过程
CREATE procedure GetNews
     (
@pagesize int,
        
@pageindex int,
        
@docount bit)
        
as
        
set nocount on
        
if(@docount=1)
        
select count(id) from news
        
else
        
begin
        
declare @indextable table(id int identity(1,1),nid int)
        
declare @PageLowerBound int
        
declare @PageUpperBound int
        
set @PageLowerBound=(@pageindex-1)*@pagesize
        
set @PageUpperBound=@PageLowerBound+@pagesize
        
set rowcount @PageUpperBound
        
insert into @indextable(nid) select id from news order by addtime desc
        
select O.id,O.source,O.title,O.addtime from news O,@indextable t where O.id=t.nid
        
and t.id>@PageLowerBound and t.id<=@PageUpperBound order by t.id
        
end
        
set nocount off
GO
posted @ 2006-12-22 10:02  海浪~~  阅读(216)  评论(0)    收藏  举报