我在閱讀關於如何高效地瀏覽大型數據集,因爲我不滿意Row_Number
和Fetch
是最差的。從這個sql server文章頁面的高效方式
這是文章: 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
這個演示代碼看起來OK(如你看到:)其他演示)。上面的代碼只是因爲他在SELECT @first_id = employeeID FROM employees ORDER BY employeeid
中使用Order By employeeid
。
比方說,我有一個名爲FirstName
的字段,並希望以此來排序。那我如何寫上述程序?上述程序顯然不起作用,因爲那樣我們不能寫WHERE employeeid >= @first_id
,因爲如果我們按名稱排序,我們不能得到first_id
。這是因爲where
在order by
之前執行。
如果我們改變上面的查詢:
Select * From (SELECT e.*, d.name as DepartmentName
FROM employees e
INNER JOIN Departments D ON
e.DepartmentID = d.DepartmentID
ORDER BY e.EmployeeID) v WHERE employeeid >= @first_id
那麼它會工作,但這就意味着,上述查詢將給予更大的數據集表現極差。
那麼,我們如何將上述演示代碼用於生產使用?任何幫助表示讚賞。
您對Departments.DepartmentID有PK(或唯一)嗎? –
@Roman:這些不是我的表格。這是來自http://www.4guysfromrolla.com/webtech/042606-1.shtml的演示代碼,如問題所述。 –
如果他們不是你的表,那麼你爲什麼問「那麼,我們如何使用上面的演示代碼進入生產使用?」擬議變更的目的是什麼?它不會在FirstName上排序。 – Paparazzi