分享好友 数据库首页 频道列表

sql分页查询几种写法

SQL Server  2015-10-15 11:030

关于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,取第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 exists

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

--写法3,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,row_number()

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上一帖子看到的,row_number() 变体,不基于已有字段产生记录序号,先按条件筛选以及排好序,再在结果集上给一常量列用于产生记录序号

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()
<.....YOUR CODE.....>
select @end_date = getdate()
select datediff(ms,@begin_date,@end_date) as '毫秒'

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

10万:

sql分页查询几种写法

4.结论:

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

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

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

4.ROW_NUMBER() 的变体基于我这个测试效率实在不好。原帖在这里 http://topic.csdn.net/u/20100617/04/80d1bd99-2e1c-4083-ad87-72bf706cb536.html

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

5.简单将ROWNUMBER,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(@OrderType<>0) 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;
  }
  /// <summary>
  /// 分页获取数据列表及总行数
  /// </summary>
  /// <param name="tbName">表名</param>
  /// <param name="tbGetFields">返回字段</param>
  /// <param name="OrderFldName">排序的字段名</param>
  /// <param name="PageSize">页尺寸</param>
  /// <param name="PageIndex">页码</param>
  /// <param name="OrderType">false升序,true降序</param>
  /// <param name="strWhere">查询条件</param>
  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.必填项:tbName,OrderfldName,tbGetFields

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 <= 0
begin
 set @PageIndex = 1
end

set @strSql='select top '+str(@PageSize)+' * from ' + @tbName + '
where id>(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这么一个版本,看起来很强大,http://www.cnblogs.com/hertcloud/archive/2005/12/21/301327.html

调用:

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 Server】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
去重复的sql(Oracle) 去重复的英文
1.利用group by 去重复2.可以利用下面的sql去重复,如下  1) select id,name,sex from (select a.*,row_number() over(partition by a.id,a.set order by name) su from test a ) where su=1  2)select id,name,sex from (select a.*,row_number() over(p

0评论2023-02-10893

Oracle SQL七次提速技巧
以下SQL执行时间按序号递减。1,动态SQL,没有绑定变量,每次执行都做硬解析操作,占用较大的共享池空间,若共享池空间不足,会导致其他SQL语句的解析信息被挤出共享池。create or replace procedure proc1as beginfor i in 1..100000 loop    execute imme

0评论2023-02-10755

SQL ORACLE case when函数用法
case when 用法(1)简单case函数:格式:  case 列名   when 条件值1 then 选项1  when 条件值1 then 选项2......  else 默认值 end例如:  select   case job_level  when '1' then '1111'  when '2' then '2222'   when '3' then '3333

0评论2023-02-10564

mysql下如何执行sql脚本 执行SQL脚本
1.编写sql脚本,假设内容如下:  create database dearabao;  use dearabao;  create table niuzi (name varchar(20));  保存脚本文件,假设我把它保存在F盘的hello world目录下,于是该文件的路径为:F:\hello world\niuzi.sql2.执行sql脚本,可以有2种方法: 

0评论2023-02-10699

MySQL 5.7版本sql_mode=only_full_group_by问题
用到GROUP BY 语句查询时com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'col_user_6.a.START_TIME' which is not functionally dependent on colu

0评论2023-02-10973

Oracle迁移到MySQL性能下降的注意点 oracle数据库迁移需要注意的问题
背景:最近有较多的客户系统由原来由Oracle改造到MySQL后出现了性能问题CPU 100%,或是后台的CRM系统复杂SQL在业务高峰的时候出现堆积导致业务故障。在我的记忆里面淘宝最初从Oracle迁移到MySQL期间也遇到了很多SQL的性能问题,记忆最为深刻的子查询,当初的

0评论2023-02-10580

ORACLE中通过SQL语句(alter table)来增加、删除、修改字段
1.添加字段:alter table  表名  add (字段  字段类型)  [ default  '输入默认值']  [null/not null]  ;2.添加备注:comment on column  库名.表名.字段名 is  '输入的备注';  如: 我要在ers_data库中  test表 document_type字段添加备注  comm

0评论2023-02-10584

MySQL与Oracle 差异比较之六触发器
触发器编号类别ORACLEMYSQL注释1创建触发器语句不同create or replace trigger TG_ES_FAC_UNIT  before insert or update or delete on ES_FAC_UNIT  for each rowcreate trigger `hs_esbs`.`TG_INSERT_ES_FAC_UNIT` BEFORE INSERT on `hs_esbs`.`es_fac_u

0评论2023-02-10914

mysql where条件:某时间字段为今天的sql语句
1.查询:注册时间为今天的所有用户数:select count(*) from customer where TO_DAYS(createtime) = TO_DAYS(NOW())2.获取当前时间到凌晨24点还有多长时间:(Java中可用于判断某时间是否为今天)final Calendar cal = Calendar.getInstance();    ca

0评论2023-02-10717

mysql中的sql
变量用户变量: 在用户变量前加@系统变量: 在系统变量前加@@运算符算术运算符有: +(加), -(减), * (乘), / (除) 和% (求模) 五中运算位运算符有:(位于), | (位或), ^ (位异或), ~ (位取反),(位右移),(位左移)比较运算符有: = (等于),(大于),(小于), = (大

0评论2023-02-10936

Oracle的HINT可以强制指定SQL的执行计划,比如选择索引、表的连接顺序以及表的连接方式等等。(转)
在Oracle中查看所有的表: select * from tab/dba_tables/dba_objects/cat; 看用户建立的表 :  select table_name from user_tables;  //当前用户的表 select table_name from all_tables;  //所有用户的表 select table_name from dba_tables;  //包

0评论2023-02-10857

Oracle sql 子字符串长度判断
Oracle sql 子字符串长度判断 select t.* from d_table t WHEREsubstr(t.col,1,1)='8' and instr(t.col,'/')0 and length(substr(t.col,1,instr(t.col,'/')))5; 字符串的前两位都是数字:select * from d_table t WHERE regexp_like(substr(t.col,1,2), '^[

0评论2023-02-10759

Oracle、MySql、Sql Server比对
MySql:廉价(部分免费):当前,MySQL採用双重授权(DualLicensed),他们是GPL和MySQLAB制定的商业许可协议。假设你在一个遵循GPL的***(开源)项目中使用MySQL,那么你能够遵循GPL协议免费使用MySQL。否则,你须要购买MySQLAB制定的那个商业许可协议。Windows $

0评论2023-02-10441

Oracle 存储过程,临时表,动态SQL测试
--创建事务级别的结果临时表create global temporary table tmp_yshy( c1 varchar2(100), c2 varchar2(100))on commit delete rows;--创建事务级别的存储sql语句的临时表create global temporary table tmp_sql( c1 varchar2(4000))on commit delete rows;测

0评论2023-02-10508

更多推荐