3

好的,我的 SQL Server 数据库中有一个存储评论的表。我的愿望是能够使用我的数据列表中的 [Back]、[Next]、页码和 [Last] 按钮对记录进行分页。我认为最有效的方法是使用只返回特定范围内一定数量行的存储过程。这是我想出的

@PageIndex INT, 
@PageSize INT,
@postid int


AS
 SET NOCOUNT ON  
 begin

WITH tmp AS ( 
SELECT comments.*, ROW_NUMBER() OVER (ORDER BY dateposted ASC)  AS  Row
    FROM    comments
    WHERE     (comments.postid = @postid))

SELECT tmp.*
FROM tmp
WHERE Row between 

(@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize

end

RETURN 

现在一切正常,我已经能够在我的数据列表寻呼机中实现 [Next] 和 [Back] 按钮。现在我需要所有评论的总数(不在当前页面中),以便我可以实现我的页码和寻呼机上的[Last] 按钮。换句话说,我想在我的第一个选择语句中返回总行数,即

  WITH tmp AS ( 
    SELECT comments.*, ROW_NUMBER() OVER (ORDER BY dateposted ASC)  AS  Row
        FROM    comments
        WHERE     (comments.postid = @postid))
set @TotalRows = @@rowcount

@@rowcount 不起作用并引发错误。我也不能让 count.* 工作。

有没有另一种方法来获得总行数,或者我的方法注定要失败。

4

2 回答 2

5

要获取页面的评论总数,需要单独查询:

SELECT TotalRows = COUNT(*)
FROM comments
WHERE comments.postid = @postid

将此数据带回同一查询的唯一方法是将数据存储为主存储过程上的子查询,并返回存储过程中每一行的总数。

于 2010-03-30T23:07:21.800 回答
4

我已经解决了这个问题,最后我找到了一些解决方案,这些解决方案都不是很壮观,但可以完成工作:

  1. 查询两次
  2. 将计数作为列之一返回
  3. 将结果填充到临时表中,同时将计数作为列返回

在第一个解决方案中,您将执行以下操作:

    ...
    , @Count int OUTPUT
AS 
Select @Count = (
                Select Count(*)
                From comments
                Where comments.postid = @postid
                    And Col1 = ... And Col2 = ...
                )

With NumberedResults As
    (
    Select ...
        , ROW_NUMBER() OVER( ORDER BY dateposted ASC ) As Num
    From comments
    Where Col1 = ... And Col2 = ...
    )
Select ...
From NumberedResults
Where Num Between ( @PageIndex - 1 ) * @PageSize + 1 and @PageIndex * @PageSize

明显的缺点是,如果查询很昂贵,则需要执行两次。

在第二种解决方案中,您只需将计数作为结果的一部分返回。然后,您将从业务层代码中的第一条记录中选取计数。优点是您只需执行一次昂贵的查询。缺点是您为结果中的每一行返回额外的四个字节。

With NumberedResults As
    (
    Select ...
        , ROW_NUMBER() OVER( ORDER BY dateposted ASC ) As Num
    From comments
    Where Col1 = ... And Col2 = ...
    )
Select ...
    , ( Select Count(*) From NumberedResults ) As TotalCount
From NumberedResults
Where Num Between ( @PageIndex - 1 ) * @PageSize + 1 and @PageIndex * @PageSize

第三种解决方案是第二种解决方案的变体,您将结果填充到临时表中并从第一条记录中设置 out 参数

    ...
    , @TotalCount int OUTPUT
AS

Declare @PagedResults Table (
                            Col1 ...
                            , ...
                            , TotalCount int
                            )
With NumberedResults As
    (
    Select ...
        , ROW_NUMBER() OVER( ORDER BY dateposted ASC ) As Num
    From comments
    )
Insert @PagedResults( Col1...., TotalCount )
Select ...
    , ( Select Count(*) From NumberedResults ) As TotalCount
From NumberedResults
Where Num Between ( @PageIndex - 1 ) * @PageSize + 1 and @PageIndex * @PageSize

Set @TotalCount = ( Select TOP 1 TotalCount From @PagedResults )

Select ...
From @PagedResults
于 2010-03-30T23:15:32.693 回答