基于sqlserver的四种分页方式总结
第一种:ROW_NUMBER() OVER()方式
select * from (
select *, ROW_NUMBER() OVER(Order by ArtistId ) AS RowId from ArtistModels
) as b
where RowId between 10 and 20
---where RowId BETWEEN 当前页数-1*条数 and 页数*条数---
执行结果是:
第二种方式:offset fetch next方式(SQL2012以上的版本才支持:推荐使用 )
select * from ArtistModels order by ArtistId offset 4 rows fetch next 5 rows only
--order by ArtistId offset 页数 rows fetch next 条数 rows only ----
执行结果是:
第三种方式:--top not in方式 (适应于数据库2012以下的版本)
select top 3 * from ArtistModels
where ArtistId not in (select top 15 ArtistId from ArtistModels)
------where Id not in (select top 条数*页数 ArtistId from ArtistModels)
执行结果:
第四种方式:用存储过程的方式进行分页
CREATE procedure page_Demo
@tablename varchar(20),
@pageSize int,
@page int
AS
declare @newspage int,
@res varchar(100)
begin
set @newspage=@pageSize*(@page - 1)
set @res='select * from ' +@tablename+ ' order by ArtistId offset '+CAST(@newspage as varchar(10)) +' rows fetch next '+ CAST(@pageSize as varchar(10)) +' rows only'
exec(@res)
end
EXEC page_Demo @tablename='ArtistModels',@pageSize=3,@page=5
执行结果:
ps:今天搞了一下午的分页,通过上网查资料和自己的实验,总结了四种分页方式供大家参考,有问题大家一起交流学习。
相关文章
SQL Server中判断和处理NULL值的多种方法和解决方案
在SQL Server数据库中,NULL是表示缺少数据或未知值的特殊标记,处理NULL值是SQL开发人员经常遇到的问题之一,本文将介绍SQL Server中判断和处理NULL值的不同方法,以及一些解决方案,帮助您更好地处理数据库中的NULL值情况,需要的朋友可以参考下2024-01-01
SQL Server使用SELECT INTO实现表备份的代码示例
在数据库管理过程中,有时我们需要对表进行备份,以防数据丢失或修改错误,在 SQL Server 中,可以使用 SELECT INTO 语句将数据从一个表备份到另一个表,本文通过代码示例介绍的非常详细,需要的朋友可以参考下2025-01-01
insert into tbl() select * from tb2中加入多个条件
insert into tbl() select * from tb2中加入多个条件2009-06-06


最新评论