sql server 2005引入的新方法。
select * from (select row_number() over(order by keyfield desc) as rownum, * from tablename) as t where rownum > start and rownum <= end
其中:keyfield為表tablename的乙個字段(最好是主鍵);
tablename為查詢的表名;
desc可以按需換為asc;
start為要取的結果集的起始記錄
end為要取的結果集的結尾記錄,可由:(start + pagesize)計算得出。
sql server的一般方法。
建立表:
create table [testtable] (
[id] [int] identity (1, 1) not null ,
[firstname] [nvarchar] (100) collate chinese_prc_ci_as null ,
[lastname] [nvarchar] (100) collate chinese_prc_ci_as null ,
[country] [nvarchar] (50) collate chinese_prc_ci_as null ,
[note] [nvarchar] (2000) collate chinese_prc_ci_as null
) on [primary]
go插入資料:(2萬條,用更多的資料測試會明顯一些)
set identity_insert testtable on
declare @i int
set @i=1
while @i<=20000
begin
insert into testtable([id], firstname, lastname, country,note) values(@i, ''firstname_***'',''lastname_***'',''country_***'',''note_***'')
set @i=@i+1
endset identity_insert testtable off
分頁方案一:(利用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的游標儲存過程分頁) 效率最差,但是最為通用在實際情況中,要具體分析。
輪胎生產企業最佳解決方案
輪胎製造商在從接收原材料到最後裝配和配送的所有生產階段中,都需要可靠的條碼讀取解決方案。在使用週期內要經歷多個地點 廠房以及城市或國家,因此準確的輪胎識別對管理合規性 在製品 分揀和工藝路線以及質量控制至關重要。全新的康耐視輪胎解決方案採用獲得專利的高速條碼演算法和光學字元識別 ocr 讀取技術,可...
解密LED品質影響因素及最佳解決方案
產品配套能力 除了分立led,led的組裝和供電對於它的效能 亮度和顏色等指標都有非常重要的影響。由於環境溫度 工作電流 電路結構 電壓尖峰和環境因素等都能夠影響led的效能指標,恰當的電路設計和組裝是保護led和保證效能的關鍵。led製造商也使用多種技術和不同的材料來設計電路結構和組裝,大多數情況...
校園廣播最佳解決方案數字網廣播系統
發布日期 2005 6 15 點選 1055 次 校園廣播最佳解決方案數字網廣播系統 一 典範應用 廣泛應用於擁有區域網的場所如高校 中小學校 高尚小區 現代化工廠 酒店 大廈等,進行背景 廣播 講話通知 打鈴 外語教學 聽力考試和消防緊急廣播等。二 系統概述 隨著現代科學技術與資訊科技的飛速發展,...