【问题标题】:Sql Paging/Sorting - Efficent method with dynamic sort?Sql 分页/排序 - 动态排序的有效方法?
【发布时间】:2012-02-17 20:36:56
【问题描述】:

我正在尝试实现这种分页方式:

http://www.4guysfromrolla.com/webtech/042606-1.shtml

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 

这种方法效果很好,但是,是否可以使用这种方法并进行动态字段排序?

如果我们把它改成

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.FirstName DESC

它破坏了排序...

有没有办法将这种分页方法与对不同字段进行排序的能力结合起来?

【问题讨论】:

    标签: sql pagination


    【解决方案1】:

    您需要使用此方法跟踪名字和 ID。您必须跟踪两者的原因是名字在您的数据集中可能不是唯一的,因此您可以按它和唯一的值进行排序。第一条记录的选择中的顺序必须与记录集的选择中的顺序一致。

    未经测试,但您应该明白这一点。您需要将@first_first_name 声明为类似于@first_id 所做的变量。

    DECLARE @first_first_id VARCHAR(50) -- whatever your first name field size is
    SET ROWCOUNT @startRowIndex
    SELECT @first_id = employeeID, @first_first_name = FirstName FROM employees ORDER BY FirstName DESC, employeeid
    
    SELECT e.*, d.name as DepartmentName 
    FROM employees e
    INNER JOIN Departments D ON
       e.DepartmentID = d.DepartmentID
    WHERE
        e.FirstName <= @first_first_name
        OR (e.FirstName = @first_first_name AND employeeid >= @first_id)
    ORDER BY e.FirstName DESC, employeeid
    

    【讨论】:

      猜你喜欢
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多