SqlServer分页查询

例如要从数据库的第10条数据开始查询5条数据,SqlServer查询语句如下:

select top 5 * from table_name where id not in(
select top 10 id from table_name order by id desc) order by id desc

 

例:

SELECT TOP 5 * FROM MES_MMS_MLOT WHERE MMS_MLOT_SID NOT IN (
select top 10 MMS_MLOT_SID from MES_MMS_MLOT order by MMS_MLOT_SID desc) order by MMS_MLOT_SID desc

 

 

上述的方法不推荐,推荐使用下述方法

 1、ROW_NUMBER OVER方式

 

-- 分页查询公式-row_number()-优化版本
select * 
from (
    -- rownumber是别名,可按自己习惯取
    select top (@pageIndex*@pageSize) row_number() over(order by 主键 asc) 
    as rownumber,* 
    from 表名) temp_row
where rownumber>((@pageIndex-1)*@pageSize);


-- 分页查询第2页,每页有10条记录
select * 
from (
    -- 子查询,限制了返回前20条数据
    select top 20 row_number() over(order by uid asc) as rownumber,* 
    from tb_user) temp_row
    --限制起始行标
where rownumber>10;

 

2、offset fetch next方式(SQL2012及以上的版本才支持:推荐使用 )

说明:
offset 10 rows ,将前10条记录舍去,fetch next 10 rows only ,向后再读取10条数据。
句式 offset...rows fetch nect ..rows only,注意rows和末尾的only 不要写漏掉了,并且 这种方式必须要接着Order by XX 使用,不然会报错 。
offset 是跳过多少行,
next是取接下来的多少行,

-- 分页查询公式-offset /fetch next
select * from 表名
order by 主键 或 其他索引列 
-- @pageIndex:页码、@pageSize:每页记录数
offset ((@pageIndex-1)*@pageSize) rows
fetch next @pageSize rows only;

--查询第1页,每页都10条记录
select * from tb_user
order by uid
offset 0 rows
fetch next 10 rows only ;
-- 分页查询第2页,每页有10条记录 
select * from tb_user
order by uid 
offset 10 rows 
fetch next 10 rows only ;

 

posted on 2021-06-15 14:39  写个笔记  阅读(386)  评论(0编辑  收藏  举报

导航