我尝试创建一个存储过程,它需要一个索引从哪里开始、要显示的最大行数和一个位置。它们返回
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
我重新编写了你的代码,因此它使用 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 或更高版本)
我重新编写了你的代码,因此它使用了 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)