之前想实现分页功能,在网上看了下,要实现分页读取而不是分页预览,一个较好的方法是写存储过程,有一个感觉可以,不过没有试验:
在存储过程中加入一个小算法,直接输入参数(页数)读取比较划算,存储过程如下C#:
create procedure class_c
@x int
as
select classId,ClassName,EntranceDate,Remark from (
--按scgrade降序排列,并按row_number() 分组
select row_number() over (order by classId ASC) as num,*from Class)
--加入算法,动态获取X的范围
as n where num between @x*5-4 and @x*5
然后又看到一篇文章,写的不错:http://www.williamlong.info/info/archives/241.html
上面的方法有通用的,我主要是学习了一下上面较为简单又较好的语句,并仿照写了一个分页的存储过程:
CREATE PROCEDURE proc_Paging
@pageSize int,
@currentPage int
AS
BEGIN
SET NOCOUNT ON;
select top @pageSize * from dbo.tbTestWellLogInfo
where num>
(select MAX(num) from
(select top((@currentPage-1)*@pageSize) num from dbo.tbTestWellLogInfo order by num)as T
)
order by num
END
GO
但是报错,说' select top @pageSize * from'中的@pageSize有语法错误,就重新采用了网上的拼接字符串方法,虽然成功执行了,但还是不很理解为什么那样修改就行:
CREATE PROCEDURE proc_Paging
@pageSize int,
@currentPage int
AS
BEGIN
SET NOCOUNT ON;
declare @str varchar(1000)
select @str = ''
select @str='select top'+ @pageSize+' * from dbo.tbTestWellLogInfo
where num>
(select MAX(num) from
(select top(('+@currentPage+'-1)*'+@pageSize+') num from dbo.tbTestWellLogInfo order by num)as T
)
order by num'
exec(@str)
END
GO
但是这样做虽然可以执行成功生成存储过程,但是执行一下,输入参数会发现有错误。再次修改原来语句,发现需要将变量@pageSize括起来:
CREATE PROCEDURE proc_Paging
@pageSize int,
@currentPage int
AS
BEGIN
SET NOCOUNT ON;
select top (@pageSize) * from dbo.tbTestWellLogInfo
where num>
(select MAX(num) from
(select top((@currentPage-1)*@pageSize) num from dbo.tbTestWellLogInfo order by num)as T
)
order by num
END
GO
这样终于可以执行成功了,但是执行,输入参数,发现第一页的数据不能读出来,因为currentPage=1时,select max(num) from null 为null。最后附上正确语句:
ALTER PROCEDURE proc_Paging
@pageSize int,
@currentPage int
AS
BEGIN
SET NOCOUNT ON;
if(@currentPage=1)select top (@pageSize) * from dbo.tbTestWellLogInfo
else begin
select top (@pageSize) * from dbo.tbTestWellLogInfo
where num>
(select MAX(num) from
(select top((@currentPage-1)*@pageSize) num from dbo.tbTestWellLogInfo order by num)as T
)
order by num
end
END
GO