如何在应用分页后获取总行数

时间:2017-04-06 05:33:46

标签: sql-server

我正在使用@skip和@take参数进行分页。我需要分页后的总行数。我怎样才能将其作为表现的最佳方式?

CREATE PROCEDURE Search
    @Take       Int           = 10
    @Skip       Int           = 0
    @TotalRows  Int Out
AS

    BEGIN
    Select
                    RowNo, FirstName, LastName
                From
                    (
                        Select Row_Number()Over(Order By Id) As [RowNo],
                            FirstName,
                            LastName    
                        From Users                  
                    ) tblTemp
                Where RowNo > @Skip And RowNo <= @Take + @Skip

                Set @TotalRows = ??? -- I need the number of total rows after applying paging. How can I do this?
    END

1 个答案:

答案 0 :(得分:0)

您可以使用@@ROWCOUNT

程序

CREATE PROCEDURE Search
    @Take       Int           = 10,
    @Skip       Int           = 0,
    @TotalRows  Int Out
AS
BEGIN
    Select
        RowNo, 
        FirstName, 
        LastName
    From (
        Select 
            Row_Number()Over(Order By Id) As [RowNo],
            FirstName,
            LastName    
        From Users                  
    ) tblTemp
    Where RowNo > @Skip And RowNo <= @Take + @Skip

    Set @TotalRows = @@ROWCOUNT
END

你可以像处理一样调用proc;

declare @total_rows int;
exec search 10, 0, @total_rows output
select @total_rows