這幾天剛好碰到數據的分頁查詢,覺得不錯,Mark一下,方法有兩種,都是使用select top,效率如何就不在這討論 方法1:利用select top配合not in(或者not exists),查詢第n頁的時候,過濾掉n-1頁的數據即可,示例假設每頁查詢數量為5,查詢第3頁的數據; Select ...
這幾天剛好碰到數據的分頁查詢,覺得不錯,Mark一下,方法有兩種,都是使用select top,效率如何就不在這討論
方法1:利用select top配合not in(或者not exists),查詢第n頁的時候,過濾掉n-1頁的數據即可,示例假設每頁查詢數量為5,查詢第3頁的數據;
Select Top 5 UserCode,UserName from userInfo where UserCode not in (select top ((3-1)*5) UserCode from UserInfo order by UserCode asc) order by UserCode asc
前15行的數據
第三頁的數據
註意查詢的時候order by 必須使用相同的列及排列;
方法2:利用Row_Number()內置函數,先給查詢的表加上一列ID,然後查詢第幾頁就很簡單了 between ..and...
select UserCode,UserName,PassWord From
(Select UserCode,UserName,PassWord,Rn=Row_Number() OVER(order by UserCode desc) From UserInfo) AS T
Where t.Rn between (3-1)*5 and 3*5
當然實際應用中每頁記錄數量,查詢第幾頁都可以使用參數來代替。