2011-10-10 61 views
2

由於前兩個評論我已經刪除了所有我自己的代碼,並直接從4個人放在這裏的例子。高效的sql服務器分頁

我對'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 
+0

高效分頁縱觀複雜我。 –

+0

'請在沒有上下文的情況下調試我的代碼' - 不用了,謝謝。 – JNK

+0

這個例子看起來不錯,因爲一個Employee只在一個部門中,所以連接不會改變行數。儘管如此,這是一種SQL Server 2000方法。 'row_number'在2005+更容易 –

回答

2

可以使用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 
+2

感謝Magnus。這是我總是這樣做的方式,但最近讀到它對大數據集不適用。你怎麼看? –

+0

你在哪裏讀到的?據我所知,這是做這件事的最好方法。 – Magnus

+0

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