MSSQL查询数据分页

方法1:利用select top配合not in(或者not exists),查询第n页的时候,过滤掉n-1页的数据即可,示例假设每页查询数量为5,查询第3页的数据;

Select Top 5 UserCode,UserName from userInfo where UserCode not in (select top ((3-1)*5) UserCode from UserInfo order by UserCode asc) order by UserCode asc

前15行的数据

第三页的数据

注意查询的时候order by 必须使用相同的列及排列;

 

方法2:利用Row_Number()内置函数,先给查询的表加上一列ID,然后查询第几页就很简单了 between ..and...

select UserCode,UserName,PassWord From

(Select UserCode,UserName,PassWord,Rn=Row_Number()  OVER(order by UserCode desc) From UserInfo) AS T

Where t.Rn between (3-1)*5 and 3*5

当然实际应用中每页记录数量,查询第几页都可以使用参数来代替。

posted @ 2022-02-17 16:13  大大章鱼  阅读(621)  评论(0编辑  收藏  举报