在sql server中使用ROW_NUMBER分页时,执行计划中的执行次数过多

时间:2016-08-25 08:26:29

标签: sql-server-2008 paging row-number

在SQL SERVER 2008中。

我的桌子有很大的行。我使用row_number实现了分页。但我认为这不是有效的成本。

执行计划 enter image description here

执行次数=> 15005。 如果我将15005更改为150005,那么,Excutions的数量将增加到150005。

可以吗?有没有减少这个数量的方法?

这是我的查询

SELECT *
FROM 
(
    select *, ROW_NUMBER() OVER(ORDER BY send_time) as row_num
    FROM [dbo].[GlobalMessage]
    WHERE active =1
) as T
WHERE row_num >= 15000 and row_num < 15005

和表格信息

CREATE TABLE [dbo].[GlobalMessage](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [active] [int] NOT NULL,
    [message] [nvarchar](200) NOT NULL,
    [send_time] [int] NOT NULL,
 CONSTRAINT [PK_GlobalMessage] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE NONCLUSTERED INDEX [NonClusteredIndex-20160823-125945] ON [dbo].[GlobalMessage]
(
    [active] ASC,
    [send_time] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

1 个答案:

答案 0 :(得分:0)

使用OFFSET / FETCH使用以下语法(假设SQL Server 2012或更高版本)可能会获得更好的结果:

;WITH pg AS 
(
  SELECT [key_column] 
  FROM [dbo].[GlobalMessage]
  ORDER BY send_time
  OFFSET @PageSize * (@PageNumber - 1) ROWS
  FETCH NEXT @PageSize ROWS ONLY
)
SELECT t.*
  FROM [dbo].[GlobalMessage] AS t
  INNER JOIN pg ON t.[key_column] = pg.[key_column] -- or EXISTS
  ORDER BY send_time;

以下是关于此方法的性能和使用的优秀文章:http://sqlperformance.com/2015/01/t-sql-queries/pagination-with-offset-fetch

为SQL Server 2008添加替代方案:

declare @rowsPerPage as bigint; 
declare @pageNum as bigint; 
set @rowsPerPage=25; 
set @pageNum=10;   

With SQLPaging As   ( 
    Select Top(@rowsPerPage * @pageNum) ROW_NUMBER() OVER (ORDER BY ID asc) 
    as resultNum, * 
    FROM [dbo].[GlobalMessage] 
     WHERE active =1
    )
select * from SQLPaging with (nolock) where resultNum > ((@pageNum - 1) * @rowsPerPage)