日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SQL?Server實現分頁方法介紹_MsSql

作者:.NET開發菜鳥 ? 更新時間: 2022-05-17 編程語言

一、創建測試表

CREATE TABLE [dbo].[Student](
    [id] [int] NOT NULL,
    [name] [nvarchar](50) NULL,
    [age] [int] NULL)

二、創建測試數據

declare @i int
set @i=1
while(@i<10000)
begin
    insert into Student select @i,left(newid(),7),@i+12
    set @i += 1
end

三、測試

1、使用top關鍵字

top關鍵字表示跳過多少條取多少條

declare @pageCount int  --每頁條數
declare @pageNo int  --頁碼
declare @startIndex int --跳過的條數
set @pageCount=10
set @pageNo=3
set @startIndex=(@pageCount*(@pageNo-1)) 
select top(@pageCount) * from Student
where ID not in
(
  select top (@startIndex) ID from Student order by id 
) order by ID

測試結果:

2、使用row_number()函數

declare @pageCount int  --頁數
declare @pageNo int  --頁碼
set @pageCount=10
set @pageNo=3
--寫法1:使用between and 
select t.row,* from 
(
   select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row between (@pageNo-1)*@pageCount+1 and @pageCount*@pageNo
--寫法2:使用 “>”運算符
 select top (@pageCount) * from 
(
   select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row >(@pageNo-1)*@pageCount
--寫法3:使用and運算符 
select top (@pageCount) * from 
(
   select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row >(@pageNo-1)*@pageCount and t.row<(@pageNo)*@pageCount+1

四、總結

ROW_NUMBER()只支持sql2005及以上版本,top有更好的可移植性,能同時適用于sql2000及以上版本、access。

原文鏈接:https://www.cnblogs.com/dotnet261010/p/10784315.html

欄目分類
最近更新