SQL Server优化器 - 不工作?

时间:2012-01-11 20:01:41

标签: sql sql-server tsql stored-procedures

我发现了以下有关A More Efficient Method for Paging Through Large Result Sets

的文章

他们说:

  

在这种情况下也可以使用的优化器技巧是a   单个变量设置为潜在的值列表,它将得到   分配了列表中最后一项的值。

然后他们提供以下样本:

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没有改变它的价值。 有什么想法?

1 个答案:

答案 0 :(得分:4)

因为您没有指定@first_id是输出参数 - 您将传递给 sp_Executesql,但是没有将其取回。 This article解释了如何在sp_Executesql中使用输出参数。