sql分页查询的方法

今天爱站小编将为大家介绍sql分页查询的方法,其实我们也可以在网上查找到很多关于SQL语句分页的内容sql分页查询的方法,那么下面就是小编整理总结出已知的分页,以便方便大家查询。

1.创建测试环境,(插入100万条数据大概耗时5分钟)。

create database DBTest
use DBTest
 
--创建测试表
create table pagetest
(
id int identity(1,1) not null,
col01 int null,
col02 nvarchar(50) null,
col03 datetime null
)
 
--1万记录集
declare @i int
set @i=0
while(@i<10000)
begin
 insert into pagetest select cast(floor(rand()*10000) as int),left(newid(),10),getdate()
 set @i=@i+1
end

2.几种典型的分页sql,下面例子是每页50条,198*50=9900数据库sql分页查询,取第199页数据。

–写法1,not in/top

select top 50 * from pagetest
where id not in (select top 9900 id from pagetest order by id)
order by id

–写法2,not

select top 50 * from pagetest
where not exists
(select 1 from (select top 9900 id from pagetest order by id)a where a.id=pagetest.id)
order by id

–写法3sql分页查询的方法,max/top

select top 50 * from pagetest
where id>(select max(id) from (select top 9900 id from pagetest order by id)a)
order by id

–写法4,()

select top 50 * from
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber>9900
 
select * from
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber>9900 and rownumber<9951
 
select * from
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber between 9901 and 9950

–写法5,在csdn上一帖子看到的,() 变体,不基于已有字段产生记录序号,先按条件筛选以及排好序数据库sql分页查询,再在结果集上给一常量列用于产生记录序号

select *
from (
 select row_number()over(order by tempColumn)rownumber,*
 from (select top 9950 tempColumn=0,* from pagetest where 1=1 order by id)a
)b
where rownumber>9900

3.分别在1万,10万(取1990页),100(取19900页)记录集下测试。

测试sql:

declare @begin_date datetime
declare @end_date datetime
select @begin_date = getdate()

select @end_date = getdate()
select datediff(ms,@begin_date,@end_date) as '毫秒'

1万:基本感觉不到差异。

10万:

4.结论:

1.max/top,()都是比较不错的分页方法。相比()只支持及以上版本,max/top有更好的可移植性,能同时适用于,。

2.not 感觉是要比not in效率高一点点。

数据库sql分页查询

3.()的3种不同写法效率看起来差不多。

4.() 的变体基于我这个测试效率实在不好。原帖在这里

PS.上面的分页排序都是基于自增字段id。测试环境还提供了int,,类型字段,也可以试试。不过对于非主键没索引的大数据量排序效率应该是很不理想的。

5.简单将,max/top的方式封装到存储过程。

ROWNUMBER():
ALTER PROCEDURE [dbo].[Proc_SqlPageByRownumber]
(
 @tbName VARCHAR(255),   --表名
 @tbGetFields VARCHAR(1000)= '*',--返回字段
 @OrderfldName VARCHAR(255),  --排序的字段名
 @PageSize INT=20,    --页尺寸
 @PageIndex INT=1,    --页码
 @OrderType bit = 0,    --0升序,非0降序
 @strWhere VARCHAR(1000)='',  --查询条件
 --@TotalCount INT OUTPUT   --返回总记录数
)
AS
-- =============================================
-- Author:  allen (liyuxin)
-- Create date: 2012-03-30
-- Description: 分页存储过程(支持多表连接查询)
-- Modify [1]: 2012-03-30
-- =============================================
BEGIN
 DECLARE @strSql VARCHAR(5000) --主语句
 DECLARE @strSqlCount NVARCHAR(500)--查询记录总数主语句
 DECLARE @strOrder VARCHAR(300) -- 排序类型
 --------------总记录数---------------
 IF ISNULL(@strWhere,'') '' 
   SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where 1=1 '+ @strWhere
 ELSE SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
 
 --exec sp_executesql @strSqlCount,N'@TotalCout int output',@TotalCount output
 --------------分页------------
 IF @PageIndex <= 0 SET @PageIndex = 1
 IF(@OrderType0) SET @strOrder=' ORDER BY '+@OrderfldName+' DESC '
 ELSE SET @strOrder=' ORDER BY '+@OrderfldName+' ASC '
 SET @strSql='SELECT * FROM 
 (SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+ @tbGetFields+' FROM ' + @tbName + ' WHERE 1=1 ' + @strWhere+' ) tb 
 WHERE tb.RowNo BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND ' +str(@PageIndex*@PageSize)
 exec(@strSql)
 SELECT @TotalCount
END

public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, Int32 Size, object Value)
  {
   return MakeParam(ParamName, DbType,Size, ParameterDirection.Input, Value);
  }
  public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType)
  {
   return MakeParam(ParamName, DbType, 0, ParameterDirection.Output, null);
  }
  public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
  {
   SqlParameter param;
   if (Size > 0)
    param = new SqlParameter(ParamName, DbType, Size);
   else
    param = new SqlParameter(ParamName, DbType);
   param.Direction = Direction;
   if (!(Direction == ParameterDirection.Output && Value == null))
    param.Value = Value;
   return param;
  }
  /// 
  /// 分页获取数据列表及总行数
  /// 
  /// 表名
  /// 返回字段
  /// 排序的字段名
  /// 页尺寸
  /// 页码

数据库sql分页查询

/// false升序,true降序 /// 查询条件 public static DataSet GetPageList(string tbName, string tbGetFields, string OrderFldName, int PageSize, int PageIndex, string strWhere) { SqlParameter[] parameters = { MakeInParam("@tbName",SqlDbType.VarChar,255,tbName), MakeInParam("@tbGetFields",SqlDbType.VarChar,1000,tbGetFields), MakeInParam("@OrderfldName",SqlDbType.VarChar,255,OrderFldName), MakeInParam("@PageSize",SqlDbType.Int,0,PageSize), MakeInParam("@PageIndex",SqlDbType.Int,0,PageIndex), MakeInParam("@OrderType",SqlDbType.Bit,0,OrderType), MakeInParam("@strWhere",SqlDbType.VarChar,1000,strWhere), // MakeOutParam("@TotalCount",SqlDbType.Int) }; return RunProcedure("Proc_SqlPageByRownumber", parameters, "ds"); }

调用:

public DataTable GetList(string tbName, string tbGetFields, string OrderFldName, int PageSize, int PageIndex, string strWhere, ref int TotalCount)
  {
   DataSet ds = dal.GetList(tbName, tbGetFields, OrderFldName, PageSize, PageIndex, strWhere);
   TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
   return ds.Tables[0];
  }

注意:多表连接时需注意的地方

1.必填项:,,

2.实例:

tbName =“UserInfo u INNER JOIN Department d ON u.DepID=d.ID”
  tbGetFields=“u.ID AS UserID,u.Name,u.Sex,d.ID AS DepID,d.DefName”
  OrderfldName=“u.ID,ASC|u.Name,DESC” (格式:Name,ASC|ID,DESC)
  strWhere:每个条件前必须添加 AND (例如:AND UserInfo.DepID=1 )

Max/top:(简单写了下,需要满足主键字段名称就是”id”)

create proc [dbo].[spSqlPageByMaxTop]
@tbName varchar(255),  --表名
@tbFields varchar(1000),  --返回字段
@PageSize int,    --页尺寸
@PageIndex int,    --页码
@strWhere varchar(1000), --查询条件
@StrOrder varchar(255), --排序条件
@Total int output   --返回总记录数
as
declare @strSql varchar(5000) --主语句
declare @strSqlCount nvarchar(500)--查询记录总数主语句
--------------总记录数---------------
if @strWhere !=''
begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where '+ @strWhere
end
else
begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
end
--------------分页------------
if @PageIndex (select max(id) from (select top '+str((@PageIndex-1)*@PageSize)+' id from ' + @tbName + ''+@strOrder+')a)
'+@strOrder+''
exec sp_executesql @strSqlCount,N'@TotalCout int output',@Total output
exec(@strSql)

园子里搜到Max/top这么一个版本,看起来很强大,

调用:

declare @count int
--exec [dbo].[spSqlPageByRownumber]'pagetest','*',50,20,'','order by id asc',@count output
exec [dbo].[spSqlPageByMaxTop]'pagetest','*',50,20,'','order by id asc',@count output
select @count

以上就是本文为大家介绍关于sql分页查询的方法数据库sql分页查询,如您认为此条经验对你有所帮助,别忘了最后支持一下我哦,希望大家喜欢。

公告:
1. 本站所有资源来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长处理!
6. 本站不售卖代码,资源标价只是站长收集整理的辛苦费!如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
7. 站长QQ号码 2205675299

资源库 - 资源分享下载网 » sql分页查询的方法

常见问题FAQ

关于资源售价和售后服务的说明?
本站所有资源的标价均为本站收集资源的辛苦费,不代表资源本身的价值。软件是高智慧高价值的商品,不可能是白菜价。本站资源标价只是赞助费用,收取的赞助费仅用来维持本站的日常运营!毕竟收集整理资料需要投入云计算资源和站长大量的精力。
代码有没有售后服务和技术支持?
由于代码的运行具有不可预见性,本站不保证代码完整可运行,不提供技术支持和售后服务。 本站原创代码都是站长自己开发的,可以有偿提供技术支持服务。 网站里标明【亲测】的代码都是站长亲测过的,其他的代码由于精力有限,没有一一测试,不能保证代码就一定能够使用,更没有技术支持服务,下载前请自行斟酌。
有没有搭建服务?
由于搭建服务比较费时费力,所以本站除了原创代码外均不提供搭建服务。本站分享代码纯属兴趣爱好,不以盈利为目的,请勿咨询有没有搭建服务,谢谢理解。
链接地址失效了怎么办?
请带上资源链接地址联系客服,工作时间内我们看到后将第一时间回复。
关于解压密码
本站资源一般都没有加密,如果发现需要解压密码的,那么就输入 hao.35dc.com 试试。

发表评论

资源库,由老程序员细心甄别、精心筛选,只为提供优质的源码资源

关于我们 联系我们