读书人

分页储存

发布时间: 2012-09-27 11:11:17 作者: rapoo

分页存储
方法一:利用新增的排列函数(Row_number() over)实现分页(sql 2005)。其原理就是通过此函数与页面大小的商产生页号,从而根据页号就可以查询出当前页内容。

首先创建如下一张表,并为其添加数据(省略)

CREATE TABLE SalesHistory(            SaleID INT IDENTITY(1,1),            Product VARCHAR(30),             SaleDate SMALLDATETIME,             SalePrice MONEY)


插入数据..........

--Row_Number() over分页alter procedure proPageAccessByRowNumber(@pageNumber int,--页号@pageSize int --页面大小)asbeginset nocount on --关掉返回计数(T—SQL语句所影响的行数)select * from(select ceiling(row_number() over(order by saleid)/(@pageSize*1.0)) as row_number,* from saleshistory) as temptablewhere row_number=@pageNumber--row_number函数的用途是非常广泛,这个函数的功能是为查询出来的--每一行记录生成一个序号--ceiling作用是对数字取整为最接近的整数或最接近的多个有效数字。 0.22~1--子查询的是产生一张带页号的临时表,然后在根据当前页号来查询。set nocount offendexec  proPageAccessByRowNumber@pageNumber=12,@pageSize=5




方法二:通过两次Top翻转实现分页。其原理就是通过对“剩余记录”的查询翻转实现分页,理解这种方法的核心就是要理解“剩余记录”,那它到底是什么呢?其实大家通过字面就可以理解一二了,比如说一张表有recordCount条记录,当前页号pageIndex,页面大小是pageSize条记录,那么剩余记录(residualRecord) = recordCount - pageSize*pageIndex。下面是在sql2000上的代码:
--top分页alter procedure proPageAccessByTop(@pageIndex int,--页面索引(从0开始)@pageSize int,--页面大小@recordCount int output,--总记录数@pageCount int output--总页面数)asbegin--赋值总记录数select @recordCount=count(*) from saleshistory--赋值总页面数set @pageCount=ceiling(@recordCount*1.0/@pageSize)--申明“剩余记录”和sql查询字符串变量declare @residualRecord intdeclare @sql nvarchar(1000)--计算剩余记录并赋值set @residualRecord=@recordCount-@pageIndex*@pageSize--当第一页时,直接一次top语句if(@pageIndex=0 or @pageCount<=1)beginset @sql=N'select top'+str(@pageSize)+' * from saleshistory'end--当最后一页时,对剩余记录进行查询操作if(@pageIndex=@pageCount-1)beginset @sql=N'select * from (select top'+str(@residualRecord)+' * from saleshistory order by saleid desc) t order by saleid asc'end--否则,top两次翻转。首先,通过降序排列在整张表中筛选出所有剩余记录,然后在对这些记录进行翻转排序取出前@pageSize条记录。elsebeginset @sql=N'select top '+str(@pageSize)+'* from (select top'+str(@residualRecord)+'* from saleshistory order by saleid desc) t order by saleid asc'endendexec(@sql)

读书人网 >其他数据库

热点推荐