【问题标题】:Efficient sql server paging高效的sql server分页
【发布时间】:2011-10-10 20:12:04
【问题描述】:

由于前两个 cmets,我删除了所有我自己的代码,并将示例直接从 4 个人那里放在这里。

我对“select @first_id”的编码方式很感兴趣。该示例显示了使用连接提取的行,我希望 first_id 不是一个有效的起点,因为它不使用相同的连接语法。

CREATE  PROCEDURE [dbo].[usp_PageResults_NAI] 
(
    @startRowIndex int,
    @maximumRows int
)
AS

DECLARE @first_id int, @startRow int

-- A check can be added to make sure @startRowIndex isn't > count(1)
-- from employees before doing any actual work unless it is guaranteed
-- the caller won't do that

-- Get the first employeeID for our page of records
SET ROWCOUNT @startRowIndex
SELECT @first_id = employeeID FROM employees ORDER BY employeeid

-- Now, set the row count to MaximumRows and get
-- all records >= @first_id
SET ROWCOUNT @maximumRows

SELECT e.*, d.name as DepartmentName 
FROM employees e
   INNER JOIN Departments D ON
       e.DepartmentID = d.DepartmentID
WHERE employeeid >= @first_id
ORDER BY e.EmployeeID

SET ROWCOUNT 0

GO 

【问题讨论】:

  • 对我来说看起来很复杂。
  • Please debug my code with no context - 不,谢谢。
  • 这个例子看起来不错,因为员工正好在一个部门,所以连接不会改变行数。这是一种 SQL Server 2000 方法。 row_number 2005+ 更容易

标签: sql-server-2008 custom-paging


【解决方案1】:

您可以使用ROW_NUMBER()进行高效分页

DECLARE @skipRows Int = 10 --Change to input parameter to sp
DECLARE @takeRows Int = 20 --Change to input parameter to sp

SELECT *
FROM (
    SELECT 
         ROW_NUMBER() OVER (ORDER BY a.DateCreated) As RowNumber, 
         a.PKID, 
         a.AlertUrl, 
         a.AlertDescription, 
         a.Users_PKID_creator, 
         dbo.Users_GetFullName(a.Users_PKID_creator) as Users_FullName,
         a.Dealers_PKID, 
         d.Dealer,
         dbo.convertDateFromUTC(a.DateCreated, @dealers_pkid) as DateCreated,
         dbo.convertDateFromUTC(a.DateCreated, @dealers_pkid) as ComparisonDate,
         dbo.convertDateFromUTC(a.DateModified, @dealers_pkid) as DateModified,
         a.Active,
         a.Contacts_PKID,
         dbo.Contacts_GetFullName(a.Contacts_PKID) as Contacts_FullName
from     Alerts a
join     Dealers d on d.PKID = a.Dealers_PKID
where    a.DateCreated between dbo.convertDateToUTC(@datetimeDateStart, @dealers_pkid) and dbo.convertDateToUTC(@datetimeDateEnd, @dealers_pkid)
and      a.Active = @bitActive
and      a.PKID >= @first_id
    ) AS [t1]
WHERE [t1].RowNumber BETWEEN @skipRows + 1 AND @skipRows + @takeRows 

【讨论】:

  • 谢谢马格努斯。这是我一直这样做的方式,但最近读到它不适用于大型数据集。你怎么看?
  • 你在哪里读到的?据我所知,这是最好的方法。
  • 据我了解,该文章指的是 SQL Server 2000
  • 我认为 Martin Smith 刚刚评论并证明你是正确的 Magnus。
  • @KeithMyers - 代码与 2000 兼容,所以我认为这是一篇旧文章。它提出的观点仍然是正确的。 row_number 可能效率很低,因为有时最好使用不同的计划从实际检索结果的操作员那里获取结果的开头,但 row_number 不这样做。 See for example this answer
猜你喜欢
  • 2014-08-02
  • 2011-01-27
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 2010-12-17
相关资源
最近更新 更多