第一種方法:效率最高

SELECT TOP 頁大小 * FROM( SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1 )as A WHERE RowNumber > 頁大小*(頁數-1) --注解:首先利用Row_number()為table1表的每一行添加一個行號,給行號這一列取名'RowNumber' 在over()方法中將'RowNumber'做了升序排列 --然后將'RowNumber'列 與table1表的所有列 形成一個表A --重點在where條件。假如當前頁(currentPage)是第2頁,每頁顯示10個數據(pageSzie)。那么第一頁的數據就是第11-20條 --所以為了顯示第二頁的數據,即顯示第11-20條數據,那么就讓RowNumber大於 10*(2-1)
存儲過程 (表名aa)

if(exists(select* from sys.procedures where name='p_location_paging'))--如果p_location_paging這個存儲過程存在 drop proc p_location_paging --那么就刪除這個存儲過程 go create proc p_location_paging(@pageSize int, @currentPage int)--創建存儲過程,定義兩個變量'每頁顯示的條數'和'當前頁' as select top (@pageSize) * from ( select ROW_NUMBER() over(order by locid) as rowid ,* from aa )as A where rowid> (@pageSize)*((@currentPage)-1)
第二種方法:效率次之

SELECT TOP 頁大小 * --如果每頁顯示10條數據,那么這里就是查詢10條數據 FROM table1 WHERE id > --假如當前頁為第三頁,那么就需要查詢21-30條數據,即:id>20 ( SELECT ISNULL(MAX(id),0) --查詢子查詢中最大的id FROM ( SELECT TOP 頁大小*(當前頁-1) id FROM table1 ORDER BY id --因為當前頁是第三頁,每頁顯示十條數據。那么我將: 頁大小*(當前頁-1),就是獲取到了在"當前頁""前面"的20條數據。所以上面用max(id)查詢最大的id,取到這個20,那么前面的where 條件的id>20 即取到了第三頁的數據,即取21-30條數據 ) as A ) ORDER BY id

存儲過程(表名 aa) if(exists(select * from sys.procedures where name='p_location_paging')) drop proc p_location_paging go create proc p_location_paging(@pageSize int ,@currentPage int) as select top (@pageSize) * from aa where locId>(select ISNULL(MAX(locId),0) from (select top ((@pageSize)*(@currentPage-1))locid from location order by locId) as a )order by locId
第三種方法:效果最差

SELECT TOP 頁大小 * FROM table1 WHERE id NOT IN --where條件語句限定要查詢的數據不是子查詢里面包含的數據。即查詢"子查詢"后面的10條數據。即當前頁的數據 ( --如果當前頁是第二頁,每頁顯示10條數據,那么這里就是獲取當前頁前面的所有數據。 SELECT TOP 頁大小*(當前頁-1) id FROM table1 ORDER BY id ) ORDER BY id