用Scroll Cursor写了一个分页的存储过程【还没封装】,大家来评价评价
飞行石 2003-05-22 05:30:46 从各个角度来说吧,性能,目前问题等等。
代码如下:
/*************************************************************************
我重新写了一个分页的代码,使用Scroll Cursor,有一个缺点就是在
Fetch Absolute得时候资源占用率占掉总查询资源占用率的17%左右,如果能合并到
下面的那个循环里面就好了。因为While ... End 中间的查询所消耗的资源占用率
也是总资源占用率的17%。这样就能再提高性能了。游标比较占用资源,但是我觉得
对海量数据库在硬盘上搜索的话还是值得的。可以找一个10,000,000行的数据来测
试一下。
*************************************************************************/
Declare @PageIndex int --页索引【第几页】如果要创建存储过程
Declare @PageSize int --页行数【有几行】
Declare @Rowcount int --要查询的表/视图的行数
--只有这一行进行了全表查询,所以直接要求在相应的表
--建立一个相应的字段来存储这个信息,
--这里我还是简单的计算了一下
Select @rowcount = count(newsid) from wqnews
--下面两个变量可以封装在存储过程中,做为输入参数
Select @PageIndex = 5 --测试使用的页索引,指向当前第五页
Select @PageSize = 12 --测试使用的页大小,设定当前每页显示12条
Declare @PageLowerBound int
Declare @PageUpperBound int
Set @PageLowerBound=(@PageIndex-1)*@PageSize
Set @PageUpperBound=@PageLowerBound+@PageSize
--下面6个变量是一一对应要查询的表/视图中的字段
--请自行定义或者通过编程构造出来。
Declare @newsid int
Declare @heading nvarchar(100)
Declare @Author nvarchar(50)
Declare @AddTime smalldatetime
Declare @source nvarchar(100)
Declare @hits int
--下面的Table变量对应要查询的表/视图中的字段
--请自行设计结构或者通过编程构造出来。
Declare @wqnews Table(
newsid int Primary Key,
heading nvarchar(100),
author nvarchar(50),
addtime smalldatetime,
source nvarchar(100),
hits int)
Declare @i int
Select @i = 0
Declare myCursor SCROLL cursor for
Select * from wqnews
open myCursor
--游到指定行
fetch absolute @PageLowerBound from myCursor
--这里取出第一行放入指定的变量,对应要查询的表/视图中的字段
Into @newsid,@heading,@Author,@source,@addtime,@hits
--如果当前游标存在记录则进行下面的代码
If @@Fetch_Status = 0 Begin
Insert @wqnews (newsid,
heading,
author,
addtime,
source,
hits)
values (@newsid,
@heading,
@Author,
@addtime,
@source,
@hits)
while @i < @pageSize - 1 Begin
fetch next from myCursor
--这里取出第一行放入指定的变量,对应要查询的表/视图中的字段
Into @newsid,@heading,@Author,@source,@addtime,@hits
--当前行插入指定临时表
If @@Fetch_Status = 0 Begin
Insert @wqnews (newsid,
heading,
author,
addtime,
source,
hits)
values (@newsid,
@heading,
@Author,
@addtime,
@source,
@hits)
End
Select @i = @i +1
End
End
close myCursor
deallocate myCursor
Select * from @wqnews
/********************************代码结束********************************