2012-01-11 19 views
1

我發現了下面的文章約A More Efficient Method for Paging Through Large Result SetsSQL Server優化器 - 不工作?

他們說:

那也可以在這種情況下使用的優化技巧是當 單一變量設置爲一個值的潛在名單,它會得到 分配列表中最後一項的值。

然後他們提供以下樣品:

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 

基於上面提到的文章中,我已經寫了下列T-SQL存儲過程:

CREATE PROCEDURE Find_Programs 

    @programId INTEGER 

AS 

BEGIN 

    SET NOCOUNT ON; 
    DECLARE @SelectQuery NVARCHAR(2000) 

    DECLARE @first_id INTEGER 

    SET @SelectQuery = 'SELECT @first_id = bp.program_id FROM program bp WHERE bp.program_id >= @programId ORDER BY bp.program_id' 
    EXECUTE sp_Executesql @SelectQuery, N'@first_id INTEGER, @programId INTEGER', @first_id, @programId 

    PRINT 'first_id: ' + CONVERT(VARCHAR(10),@first_id); 

END 

但是當我運行EXEC dbo.Find_Programs @programId = 0我沒有輸出。看起來好像@first_id沒有改變它的價值。 任何想法爲什麼?

回答

4

因爲你沒有指定@first_id是參數 - 你傳遞 sp_executesql的,但沒有得到它背出的輸出。 This article解釋瞭如何在sp_Executesql中使用輸出參數。

+0

謝謝 - 這幫助我弄清楚,這裏的OUTPUT是指'sp_Executesql'的輸出,而不是調用'sp_Executesql'的存儲過程。 – rapt 2012-01-11 20:37:01