Sql Server分頁語句

2021-06-22 05:29:17 字數 1720 閱讀 9560

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

語句形式:

select top 10 *

from testtable

where (id not in

(select top 20 id

from testtable

order by id))

order by id

select top 頁大小 *

from testtable

where (id not in

(select top 頁大小*頁數 id

from 表

order by id))

order by id

-------------------------------------

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

語句形式:

select top 10 *

from testtable

where (id >

(select max(id)

from (select top 20 id

from testtable

order by id) as t))

order by id

select top 頁大小 *

from testtable

where (id >

(select max(id)

from (select top 頁大小*頁數 id

from 表

order by id) as t))

order by id

-------------------------------------

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

create  procedure xiaozhengge

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

@currentpage int, --第n頁

@pagesize int --每頁行數

asset 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

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

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

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

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

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

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

SQL Server分頁語句

有關分頁 sql 的資料很多,有的使用儲存過程,有的使用游標。本人不喜歡使用游標,我覺得它耗資 效率低 使用儲存過程是個不錯的選擇,因為儲存過程是經過預編譯的,執行效率高,也更靈活。先看看單條 sql 語句的分頁 sql 吧。方法1 適用於 sql server 2000 2005 select t...

SQL Server 分頁語句

表中主鍵必須為標識列,id int identity 1,1 1.分頁方案一 利用not in和select top分頁 select top 頁大小 from testtable where id notin select top 頁大小 頁數 1 id from 表 order byid ord...

SQL Server 分頁語句

表中主鍵必須為標識列,id int identity 1,1 1.分頁方案一 利用not in和select top分頁 select top 頁大小 from testtable where id notin select top 頁大小 頁數 1 id from 表 order byid ord...