定义:只能出现在Select或者Order By子句中
格式:
Row_Number() Over([Partition By col_list] Order By col_list)
解释:Over([分区列] 排序列)
为了计算排名值,优化器需要先按分区列再按排序列对数据排序
创建示例表
插入10W条数据
declare @i int,
@Title nvarchar(200),
@Content nvarchar(MAX),
@CreateAuthor varchar(50);
set @i=1
while @i<100001
begin
set @Title='标题'+convert(nvarchar(200),@i)
set @Content='内容为'+convert(nvarchar(MAX),@i)+'的帖子'
set @CreateAuthor='sina'
insert into Topics (Title,[Content],CreateAuthor) values(@Title,@Content,@CreateAuthor)
set @i=@i+1
end
创建存储过程Paging
CREATE PROCEDURE Paging
(@PageIndex INT,--页索引,从开始
@PageSize INT,--每页显示大小
@Count INT OUTPUT)--记录总数
AS
-- 创建临时表
Create Table #TopicsTemp
(RowNumber INT,
Id int,
Title nvarchar(200),
[Content] nvarchar(MAX),
CreateDate DateTime,
CreateAuthor varchar(50))
--行号上创建聚集索引
Create Unique Clustered Index idx_rn ON #TopicsTemp(RowNumber)
-- 填充临时表
INSERT INTO #TopicsTemp
SELECT ROW_NUMBER() OVER (ORDER BY Topics.Id),
Id,Title,[Content],CreateDate,CreateAuthor From Topics
-- 返回临时表中的记录总数
SELECT @Count = COUNT(id) FROM #TopicsTemp
-- 从表变量查询数据
SELECT Id,Title,[Content],CreateDate,CreateAuthor
FROM #TopicsTemp
WHERE RowNumber > (@PageIndex - 1) * @PageSize
AND RowNumber <= @PageIndex * @PageSize