佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > sql分頁查詢幾種寫法

sql分頁查詢幾種寫法

熱門標(biāo)簽:呼叫中心市場需求 AI電銷 網(wǎng)站排名優(yōu)化 Linux服務(wù)器 鐵路電話系統(tǒng) 服務(wù)外包 百度競價(jià)排名 地方門戶網(wǎng)站

關(guān)于SQL語句分頁,網(wǎng)上也有很多,我貼一部分過來,并且總結(jié)自己已知的分頁到下面,方便日后查閱

1.創(chuàng)建測試環(huán)境,(插入100萬條數(shù)據(jù)大概耗時(shí)5分鐘)。

create database DBTest
use DBTest
 
--創(chuàng)建測試表
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(@i10000)
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頁數(shù)據(jù)。

--寫法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 rownumber9951
 
select * from
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber between 9901 and 9950

--寫法5,在csdn上一帖子看到的,row_number() 變體,不基于已有字段產(chǎn)生記錄序號,先按條件篩選以及排好序,再在結(jié)果集上給一常量列用于產(chǎn)生記錄序號

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萬:

4.結(jié)論:

1.max/top,ROW_NUMBER()都是比較不錯(cuò)的分頁方法。相比ROW_NUMBER()只支持sql2005及以上版本,max/top有更好的可移植性,能同時(shí)適用于sql2000,access。

2.not exists感覺是要比not in效率高一點(diǎn)點(diǎn)。

3.ROW_NUMBER()的3種不同寫法效率看起來差不多。

4.ROW_NUMBER() 的變體基于我這個(gè)測試效率實(shí)在不好。原帖在這里 http://topic.csdn.net/u/20100617/04/80d1bd99-2e1c-4083-ad87-72bf706cb536.html

PS.上面的分頁排序都是基于自增字段id。測試環(huán)境還提供了int,nvarchar,datetime類型字段,也可以試試。不過對于非主鍵沒索引的大數(shù)據(jù)量排序效率應(yīng)該是很不理想的。

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   --返回總記錄數(shù)
)
AS
-- =============================================
-- Author:  allen (liyuxin)
-- Create date: 2012-03-30
-- Description: 分頁存儲過程(支持多表連接查詢)
-- Modify [1]: 2012-03-30
-- =============================================
BEGIN
 DECLARE @strSql VARCHAR(5000) --主語句
 DECLARE @strSqlCount NVARCHAR(500)--查詢記錄總數(shù)主語句
 DECLARE @strOrder VARCHAR(300) -- 排序類型

 --------------總記錄數(shù)---------------
 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>
  /// 分頁獲取數(shù)據(jù)列表及總行數(shù)
  /// /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");
  }

調(diào)用:

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];
  }

注意:多表連接時(shí)需注意的地方

1.必填項(xiàng):tbName,OrderfldName,tbGetFields

2.實(shí)例:

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:每個(gè)條件前必須添加 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   --返回總記錄數(shù)
as
declare @strSql varchar(5000) --主語句
declare @strSqlCount nvarchar(500)--查詢記錄總數(shù)主語句

--------------總記錄數(shù)---------------
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這么一個(gè)版本,看起來很強(qiáng)大,http://www.cnblogs.com/hertcloud/archive/2005/12/21/301327.html

調(diào)用:

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分頁查詢幾種寫法的全部內(nèi)容,希望大家喜歡。

您可能感興趣的文章:
  • SQL Server 排序函數(shù) ROW_NUMBER和RANK 用法總結(jié)
  • SQL為查詢的結(jié)果加上序號(ROW_NUMBER) 合并多個(gè)查詢結(jié)果
  • SQLSERVER 2005的ROW_NUMBER、RANK、DENSE_RANK的用法
  • php下巧用select語句實(shí)現(xiàn)mysql分頁查詢
  • sqlserver巧用row_number和partition by分組取top數(shù)據(jù)
  • 三種SQL分頁查詢的存儲過程代碼
  • mysql分頁原理和高效率的mysql分頁查詢語句
  • 二種sql分頁查詢語句分享
  • SQLSERVER分頁查詢關(guān)于使用Top方式和row_number()解析函數(shù)的不同

標(biāo)簽:蘭州 湘潭 衡水 黃山 崇左 湖南 仙桃 銅川

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《sql分頁查詢幾種寫法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    鹤岗市| 莱州市| 宿松县| 庄浪县| 昌黎县| 石泉县| 新蔡县| 循化| 东乌珠穆沁旗| 高碑店市| 高淳县| 绵竹市| 花莲县| 浮梁县| 九寨沟县| 云林县| 泰顺县| 桃江县| 青冈县| 金川县| 河南省| 纳雍县| 玛曲县| 娄底市| 方城县| 定安县| 壤塘县| 梓潼县| 绥宁县| 江北区| 农安县| 翼城县| 天等县| 沈阳市| 永丰县| 双辽市| 武城县| 霍州市| 阳山县| 河北区| 南宁市|