使用SQL语句实现真分页

在Wwb开发中,经常要用从数据库读取大量信息在页面中显示,页是指在从数据库读取数据时,一次只读取一页要显示的数据,当要显示下一页时,再从数据库中读取一定量的数据,这样就能提高页面的访问效率,并能降低服务器的压力。

可采用SQL语句来实现真分页,具体过程如下:

select * from (select *, row_number() over(order by studentid desc) rid from student where naturalCLass = '2015级软件工程(1)班') 
temp where rid > 0 and rid < 10

返回总页数的语句

**select count(*) from table where  condition** 

返回结果集合

select top 页容量 *
fromwhere 条件  and id not in 
        (select top 页容量*(当前页数-1) id 
        fromwhere 条件  order by排序条件 )
order by 排序条件

相关的存储过程为

create proc GetDataByPager
(
@startIndex int, --起始记录
@tableName  varchar(50),  --表名
@pageSize int,              --页容量
@key varchar(50),         --主键
@condition varchar(50)='1=1',  --查询条件    
@orderType varchar(50) ='desc'  --排序方式
)
as
begin
    declare @topCount int
    declare @sql varchar(1000)
    set @sql = ' select top ' + convert(varchar(20), @pageSize) + ' * from ' + @tableName + ' where ' + @condition + ' and ' + @key +   ' not in (select top '+ convert(varchar(20), @startIndex)+' '+@key + ' from ' + @tableName + ' where ' + @condition + ' order by '+@key+' '+ @orderType+') order by '+ @key+' '+@orderType
    print (@sql)
    exec (@sql)
end
发布了19 篇原创文章 · 获赞 6 · 访问量 9439

猜你喜欢

转载自blog.csdn.net/u012712556/article/details/77716139