2012-05-26 71 views
2

我使用ROW_NUMBER()函數從數據庫表中獲得50 50個項目。
@From參數是從哪個行開始抓取50行。 (第一次是51,101,151等)
我將參數@CityId傳遞給存儲過程,如果數據庫中的前60行是cityId=1cityId = 2在第61行,則此存儲過程不返回結果。
但是,如果我通過@From參數51比它返回我的結果。 我在這裏做錯了什麼?與分頁SQL SQL ROW_NUMBER()問題

SELECT RowConstrainedResult.* 
FROM (SELECT ROW_NUMBER() OVER 
(ORDER BY f.ItemCreatedOnDate DESC) AS RowNum, 
f.* 
FROM (
SELECT 
     t.ItemIdId, 
     t.ItemTypeId, 
     t.CreatedOnDate as ItemCreatedOnDate, 
     t.CityId as CityId 
FROM dbo.Items as t 
) f) AS RowConstrainedResult 
WHERE RowNum >= @From 
    AND RowNum < @From + 50 
    AND CityId = @CityId 

回答

7

在您的版本中,ROW_NUMBER()正在枚舉所有行。將cityid的謂詞移動到最裏面的選擇,ROW_NUMBER()將僅枚舉其中cityid = 2的行。

SELECT RowConstrainedResult.* 
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY f.ItemCreatedOnDate DESC) AS RowNum, 
      f.* 
    FROM (
      SELECT t.ItemIdId, 
       t.ItemTypeId, 
       t.CreatedOnDate as ItemCreatedOnDate, 
       t.CityId as CityId 
      FROM dbo.Items AS t 
      WHERE CityId = @CityId 
     ) AS f 
    ) AS RowConstrainedResult 
WHERE RowNum >= @From AND 
     RowNum < @From + 50 
+1

+1由7秒打我 –

2

我猜你想要做的是在內部選擇查詢CityId過濾器,像這樣:

SELECT RowConstrainedResult.* 
FROM (SELECT ROW_NUMBER() OVER 
(ORDER BY f.ItemCreatedOnDate DESC) AS RowNum, 
f.* 
FROM (
SELECT 
     t.ItemIdId, 
     t.ItemTypeId, 
     t.CreatedOnDate as ItemCreatedOnDate, 
     t.CityId as CityId 
FROM dbo.Items as t 
WHERE CityId = @CityId 
) f) AS RowConstrainedResult 
WHERE RowNum >= @From 
    AND RowNum < @From + 50