SQL Server 2005增加了不少新特性,其中NTILE和ROW_NUMER使得我們不再為SQL如何靈活方便的分頁傷腦筋了(不必再羨慕Oracle等數據庫了)。
下面就是一個很簡單的分頁查詢語句:
DECLARE @rows_per_page AS INTEGER
DECLARE @current_page AS INTEGER
DECLARE @total_pages AS INTEGER
-- 設置每頁的行數
SET @rows_per_page = 20
-- 設置要顯示的頁號(從1開始)
SET @current_page = 2
-- 計算總頁數
SELECT @total_pages = COUNT(*) / @rows_per_page
FROM testtable;
-- 列出指定頁的內容
WITH t AS
(
SELECT NTILE(@total_pages) OVER(ORDER BY id) AS page_number, *
FROM testtable
)
SELECT * from t
WHERE page_number = @current_page
程序簡單到可以不用說明的程度。
我們可以利用上述簡單的語句,變化排序條件和查詢表,就可以做出一個很通用的分頁查詢的存儲過程或查詢語句了。
同樣的,使用ROW_NUMBER也可以做到分頁查詢:
DECLARE @rows_per_page AS INTEGER
DECLARE @current_page AS INTEGER
DECLARE @start_row_num AS INTEGER
-- 設置每頁的行數
SET @rows_per_page = 20
-- 設置要顯示的頁號(從1開始)
SET @current_page = 2
-- 設置開始行號
SET @start_row_num = (@current_page - 1) * @rows_per_page
WITH t AS
(
SELECT ROW_NUMBER() OVER(ORDER BY id) AS row_number, *
FROM testtable
)
SELECT * from t
WHERE row_number BETWEEN @start_row_num AND @start_row_num + @rows_per_page 似乎更簡單的樣子。
至於哪種效率更高,這需要大家實際測試了。