1. 程式人生 > >幾種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,取第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萬:

 

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():

 

1 ALTER PROCEDURE [dbo].[Proc_SqlPageByRownumber]

2 (

3 @tbName VARCHAR(255), --表名

4 @tbGetFields VARCHAR(1000)= '*',--返回欄位

5 @OrderfldName VARCHAR(255), --排序的欄位名

6 @PageSize INT=20, --頁尺寸

7 @PageIndex INT=1, --頁碼

8 @OrderType bit = 0, --0升序,非0降序

9 @strWhere VARCHAR(1000)='', --查詢條件

10 --@TotalCount INT OUTPUT --返回總記錄數

11 )

12 AS

13 -- =============================================

14 -- Author: allen (liyuxin)

15 -- Create date: 2012-03-30

16 -- Description: 分頁儲存過程(支援多表連線查詢)

17 -- Modify [1]: 2012-03-30

18 -- =============================================

19 BEGIN

20 DECLARE @strSql VARCHAR(5000) --主語句

21 DECLARE @strSqlCount NVARCHAR(500)--查詢記錄總數主語句

22 DECLARE @strOrder VARCHAR(300) -- 排序型別

23

24 --------------總記錄數---------------

25 IF ISNULL(@strWhere,'') <>''

26 SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where 1=1 '+ @strWhere

27 ELSE SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName

28

29 --exec sp_executesql @strSqlCount,N'@TotalCout int output',@TotalCount output

30 --------------分頁------------

31 IF @PageIndex <= 0 SET @PageIndex = 1

32

33 IF(@OrderType<>0) SET @strOrder=' ORDER BY '+@OrderfldName+' DESC '

34 ELSE SET @strOrder=' ORDER BY '+@OrderfldName+' ASC '

35

36 SET @strSql='SELECT * FROM

37 (SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+ @tbGetFields+' FROM ' + @tbName + ' WHERE 1=1 ' + @strWhere+' ) tb

38 WHERE tb.RowNo BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND ' +str(@PageIndex*@PageSize)

39

40 exec(@strSql)

41 SELECT @TotalCount

42 END

 

 

注意:多表連線時需注意的地方

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