SQL Server存储过程与ROW_NUMBER

时间:2014-09-12 20:26:35

标签: sql-server tsql stored-procedures sql-server-2012 paging

我尝试创建一个存储过程,该过程采用索引从哪里开始,最大行显示和位置。它们会返回HouseID的列表和位置,但我还希望它包含另一个名为dbo.House的表格中的“房子名称”,该表格HouseId将其链接到那个地点。我该如何添加第二张表。

谢谢,

CREATE PROCEDURE dbo.basicHouseSearch 
    @StartIndex int,
    @MaxRows int,
    @HouseLocation NVarChar(50)
AS
BEGIN
    SET NOCOUNT ON;

    Select 
       Location.HouseID, CityTown 
    FROM
       (SELECT 
           ROW_NUMBER() OVER (ORDER by Location.HouseID) as RowNumber,
           Location.HouseID,
           CityTown
        FROM dbo.Location) Location
    WHERE 
        RowNumber >= @StartIndex 
        AND ROWNUMBER < (@StartIndex + @MaxRows) 
END
GO

2 个答案:

答案 0 :(得分:3)

我重写了你的代码所以它使用了CTE(我认为它更清晰):

;WITH CTE AS
(
    SELECT  RowNumber = ROW_NUMBER() OVER (ORDER by L.HouseID),
            L.HouseID,
            L.CityTown,
            H.Name [Name of the house]
    FROM dbo.Location L
    LEFT JOIN dbo.House H
        ON L.HouseID = H.HouseID
)
SELECT *
FROM CTE
WHERE RowNumber >= @StartIndex 
AND RowNumber < (@StartIndex + @MaxRows) 

答案 1 :(得分:3)

我重写了你的代码,所以它使用OFFSET / FETCH(我觉得它更清晰):

SELECT  L.HouseID,
        L.CityTown,
        H.Name [Name of the house]
FROM dbo.Location L
LEFT JOIN dbo.House H
    ON L.HouseID = H.HouseID
ORDER BY L.HouseID
OFFSET @StartIndex ROWS FETCH NEXT @MaxRows ONLY

(需要Sql Server 2012或更高版本)