sqlserver2005 分頁 SQL語句

2021-04-18 11:46:24 字數 1627 閱讀 8191

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

語句形式:  select top 10 *  from testtable  where (id not in            (select top20id           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

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

語句形式:    select top 10 *  from testtable  where (id >            (select max(id)           from (select top20id                   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

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

create  procedure sqlpager  @sqlstr nvarchar(4000), --查詢字串  @currentpage int, --第n頁  @pagesize int --每頁行數  as  set nocount on  declare @p1 int, --p1是游標的id   @rowcountintexec 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+1exec sp_cursorfetch @p1,16,@currentpage,@pagesize   exec sp_cursorclose @p1  set nocount off    其它的方案:如果沒有主鍵,可以用臨時表,也可以用方案三做,但是效率會低。  建議優化的時候,加上主鍵和索引,查詢效率會提高。    通過sql 查詢分析器,顯示比較:我的結論是:  分頁方案二:(利用id大於多少和select top分頁)效率最高,需要拼接sql語句  分頁方案一:(利用not in和select top分頁)   效率次之,需要拼接sql語句  分頁方案三:(利用sql的游標儲存過程分頁)    效率最差,但是最為通用

SqlServer2005分頁方案

插入測試資料200w條,可能會很久 create table student id int primary keyidentity 1 1 name nvarchar 50 age int insert student name,age values name 18 while select cou...

SQL Server 2005 分頁儲存過程

支援 多表連線查詢 group by分組查詢等。多表連線查詢時請指定字段,不要用select 返回為一結果集,有乙個輸出引數為記錄總數,配合 aspnetpager控制項使用絕配。create procedure web pager rowstotal intoutput,輸出記錄總數 tablen...

SQL Server 2005分頁儲存過程

剛開始學習分頁儲存過程的時候看到有很多長篇大論的 看起來很亂,現在有乙個很好的分頁儲存過程,分享一下 alter procedure dbo pr page helper top int null,返回前n位記錄 1 全部 ascordesc bit null,1 desc 0 asc column...