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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

SQL?Server實現(xiàn)分頁方法介紹_MsSql

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

一、創(chuàng)建測試表

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

二、創(chuàng)建測試數(shù)據(jù)

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關(guān)鍵字

top關(guān)鍵字表示跳過多少條取多少條

declare @pageCount int  --每頁條數(shù)
declare @pageNo int  --頁碼
declare @startIndex int --跳過的條數(shù)
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

測試結(jié)果:

2、使用row_number()函數(shù)

declare @pageCount int  --頁數(shù)
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:使用 “>”運(yùn)算符
 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運(yùn)算符 
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

四、總結(jié)

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

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

欄目分類
最近更新