SQL常用分頁的辦法

2021-08-30 12:02:08 字數 1848 閱讀 5039

淘二哥**專業導購

文章分類:資料庫

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

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

語句形式:

select top 頁記錄數量 *

from 表名

where (id not in

(select top (每頁行數*(頁數-1)) id

from 表名

order by id))

order by id

//自己還可以加上一些查詢條件

例: select top 2 *

from sys_material_type

where (mt_id not in

(select top (2*(3-1)) mt_id from sys_material_type order by mt_id))

order by mt_id

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

語句形式:

select top 每頁記錄數量 *

from 表名

where (id >

(select max(id)

from (select top 每頁行數*頁數 id from 表

order by id) as t)

) order by id

例: select top 2 *

from sys_material_type

where (mt_id >

(select max(mt_id)

from (select top (2*(3-1)) mt_id

from sys_material_type

order by mt_id) as t))

order by mt_id

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

create procedure sqlpager

@sqlstr nvarchar(4000), --查詢字串

@currentpage int, --第n頁

@pagesize int --每頁行數

as set nocount on

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

@rowcount int

exec sp_cursoropen @p1 output,@sqlstr,@scrollopt=1,@ccopt=1, @rowcount=@rowcount output

select ceiling(1.0*@rowcount/@pagesize) as 總頁數--,@rowcount as 總行數,@currentpage as 當前頁

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

exec sp_cursorfetch @p1,16,@currentpage,@pagesize

exec sp_cursorclose @p1

set nocount off

4.總結:

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

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

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

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

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

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

常用的sql分頁語句 sqlserver

常用的四種sqlserver分頁語句 現在有一張表pln project,裡邊有1000條資料 第一種分頁實現 假設頁數是10,現在要拿出第5頁的內容,查詢語句如下 select top 10 from pln project where project guid not in 40是這麼計算出來的...

SQL 常用sql分頁解決方案

分頁方案一 利用not in和select top分頁 語句形式 select top10 from testtable where id notin select top20 idfrom testtable order byid order byid select top頁大小 from tes...

IBatis的分頁研究 sql分頁

在看jpetstore的 時,發現它的分頁處理主要是通過返回paginatedlist物件來完成的。如 在catalogservice類中public paginatedlist getproductlistbycategory string categoryid 分頁是運算元據庫型系統常遇到的問題...