2
我有一個用數千條記錄調用的表,並希望實現分頁邏輯。在做了一些研究之後,我遇到了SQL Server 2005中引入的ROW_NUMBER()函數。我的問題是,它似乎不符合我的確切需求,我想知道如何調整存儲過程以使其按預期工作:用ROW_NUMBER()對SQL Server 2005進行過濾和分頁()
ALTER PROCEDURE dbo.irweb_Posts_CollectCategoryIdDatesRange
(
@CategoryId int,
@StartDate datetime,
@EndDate datetime,
@IsDeleted bit,
@PageIndex int,
@PageSize int,
@Offset int
)
AS
DECLARE @TotalRecords int
SELECT @TotalRecords = (
SELECT COUNT(irweb_Posts.PostId)
FROM irweb_Posts
WHERE (IsDeleted = @IsDeleted)
AND (CategoryId = @CategoryId)
AND (DateCreated >= @StartDate)
AND (DateCreated <= @EndDate)
)
SELECT *
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY DateCreated DESC) AS RowId, irweb_Posts.*
FROM irweb_Posts
) AS p
WHERE ((IsDeleted = @IsDeleted)
AND (CategoryId = @CategoryId)
AND (DateCreated >= @StartDate)
AND (DateCreated <= @EndDate)
AND ((RowId > @Offset) AND (RowId <= (@Offset + @PageSize))))
RETURN @TotalRecords
如果我執行這個存儲過程,我得到下面的結果
Running [dbo].[irweb_Posts_CollectCategoryIdDatesRange] (
@CategoryId = 7,
@StartDate = 5/1/2009 12:00:00 AM,
@EndDate = 5/31/2009 11:59:59 PM,
@IsDeleted = False,
@PageIndex = 0,
@PageSize = 20,
@Offset = 0).
RowId PostId CategoryId ParentId
--------------------- ----------- ----------- -----------
No rows affected.
(0 row(s) returned)
@RETURN_VALUE = 609
Finished running [dbo].[irweb_Posts_CollectCategoryIdDatesRange].
Running [dbo].[irweb_Posts_CollectCategoryIdDatesRange] (
@CategoryId = 7,
@StartDate = 5/1/2009 12:00:00 AM,
@EndDate = 5/31/2009 11:59:59 PM,
@IsDeleted = False,
@PageIndex = 0,
@PageSize = 210,
@Offset = 0).
RowId PostId CategoryId ParentId
--------------------- ----------- ----------- -----------
205 1173 7 0
206 1169 7 0
207 1168 7 0
208 1167 7 0
209 1165 7 0
210 1164 7 0
No rows affected.
(6 row(s) returned)
@RETURN_VALUE = 609
Finished running [dbo].[irweb_Posts_CollectCategoryIdDatesRange].
似乎行號字段不從1開始喜歡它應該。我懷疑它從1開始,而不是過濾結果集。如果我不需要分頁過濾的記錄,這不會成爲問題。我該如何做這項工作?
哇哦!太感謝了。我以前曾嘗試過,但忽略了「AS」條款 - 沒有奏效。沒想到它... 再次,謝謝! – 2009-12-07 06:28:44
我知道這個主題很好,但對於簡單的分頁選擇,這是非常出色的。那裏有太多複雜的解決方案。這只是石頭。 – horace 2012-07-11 16:25:49