三種SQL分頁法效率分析

2021-04-18 02:36:58 字數 1654 閱讀 5380

表中主鍵必須為標識列,[id] int identity (1,1)

1.分頁方案一:(利用not in和select top分頁)

語句形式:

selecttop10*

fromtesttable

where(idnotin

(selecttop20id

fromtesttable

orderbyid))

orderbyid

selecttop頁大小*

fromtesttable

where(idnotin

(selecttop頁大小*頁數id

from表

orderbyid))

orderbyid2.分頁方案二:(利用id大於多少和select top分頁)

語句形式:

selecttop10*

fromtesttable

where(id>

(selectmax(id)

from(selecttop20id

fromtesttable

orderbyid)ast))

orderbyid

selecttop頁大小*

fromtesttable

where(id>

(selectmax(id)

from(selecttop頁大小*頁數id

from表

orderbyid)ast))

orderbyid3.分頁方案三:(利用sql的游標儲存過程分頁)

create proceduresqlpager

@sqlstrnvarchar(4000),--查詢字串

@currentpageint,--第n頁

@pagesizeint--每頁行數

assetnocounton

declare@p1int,--p1是游標的id

@rowcountint

execsp_cursoropen@p1output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcountoutput

selectceiling(1.0*@rowcount/@pagesize)as總頁數--,@rowcountas總行數,@currentpageas當前頁

set@currentpage=(@currentpage-1)*@pagesize+1

execsp_cursorfetch@p1,16,@currentpage,@pagesize

execsp_cursorclose@p1

setnocountoff其它的方案:如果沒有主鍵,可以用臨時表,也可以用方案三做,但是效率會低。

建議優化的時候,加上主鍵和索引,查詢效率會提高。

通過sql 查詢分析器,顯示比較:我的結論是:

分頁方案二:(利用id大於多少和select top分頁)效率最高,需要拼接sql語句

分頁方案一:(利用not in和select top分頁) 效率次之,需要拼接sql語句

分頁方案三:(利用sql的游標儲存過程分頁) 效率最差,但是最為通用

三種SQL分頁法

三種sql分頁法 表中主鍵必須為標識列,id int identity 1,1 1.分頁方案一 利用not in和select top分頁 語句形式 select top 10 from testtable where id not in select top 20 id from testtabl...

三種SQL分頁法

三種sql分頁法 表中主鍵必須為標識列,id int identity 1,1 1.分頁方案一 利用not in和select top分頁 語句形式 select top 10 from testtable where id not in select top 20 id from testtabl...

三種SQL分頁法

三種sql分頁法 表中主鍵必須為標識列,id int identity 1,1 1.分頁方案一 利用not in和select top分頁 語句形式 select top 10 from testtable where id not in select top 20 id from testtabl...