2010-03-21 70 views
0

我試圖實現這種風格分頁:Sql尋呼/排序 - 動態排序的有效方法?

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 

它打破了排序...

有沒有什麼辦法來尋呼此方法進行排序不同領域的能力結合起來?

回答

0

您需要使用此方法跟蹤名字和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