溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

基于sqlserver的四種分頁(yè)方式總結(jié)

發(fā)布時(shí)間:2020-10-25 02:47:40 來(lái)源:腳本之家 閱讀:151 作者:鳳小九 欄目:數(shù)據(jù)庫(kù)

第一種:ROW_NUMBER() OVER()方式

select * from (
    select *, ROW_NUMBER() OVER(Order by ArtistId ) AS RowId from ArtistModels
  ) as b

where RowId between 10 and 20

---where RowId BETWEEN 當(dāng)前頁(yè)數(shù)-1*條數(shù) and 頁(yè)數(shù)*條數(shù)---     

執(zhí)行結(jié)果是:基于sqlserver的四種分頁(yè)方式總結(jié)

第二種方式:offset fetch next方式(SQL2012以上的版本才支持:推薦使用 )

select * from ArtistModels  order by ArtistId offset 4 rows fetch next 5 rows only
                  --order by ArtistId offset 頁(yè)數(shù) rows fetch next 條數(shù) rows only ----

執(zhí)行結(jié)果是:基于sqlserver的四種分頁(yè)方式總結(jié)

第三種方式:--top not in方式 (適應(yīng)于數(shù)據(jù)庫(kù)2012以下的版本)

select top 3 * from ArtistModels
where ArtistId not in (select top 15 ArtistId from ArtistModels)

------where Id not in (select top 條數(shù)*頁(yè)數(shù)  ArtistId  from ArtistModels)  

執(zhí)行結(jié)果:基于sqlserver的四種分頁(yè)方式總結(jié)

第四種方式:用存儲(chǔ)過(guò)程的方式進(jìn)行分頁(yè)  

CREATE procedure page_Demo
@tablename varchar(20),
@pageSize int,
@page int
AS
declare @newspage int,
@res varchar(100)
begin
set @newspage=@pageSize*(@page - 1)
set @res='select * from ' +@tablename+ ' order by ArtistId offset '+CAST(@newspage as varchar(10)) +' rows fetch next '+ CAST(@pageSize as varchar(10)) +' rows only'
exec(@res)
end
EXEC page_Demo @tablename='ArtistModels',@pageSize=3,@page=5

執(zhí)行結(jié)果:基于sqlserver的四種分頁(yè)方式總結(jié)

ps:今天搞了一下午的分頁(yè),通過(guò)上網(wǎng)查資料和自己的實(shí)驗(yàn),總結(jié)了四種分頁(yè)方式供大家參考,有問(wèn)題大家一起交流學(xué)習(xí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI