0

我在运行查询 2 次(获取数据和总行数)的 SQL Server 2005 上进行分页时遇到问题。我的演示过程基于 Northwind 数据库。请帮助我如何在不再次查询的情况下获得总行数。

CREATE PROCEDURE [dbo].[SearchEmployees] 
     @search nvarchar(4000)
    ,@orderBy varchar(200)
    ,@PageSize int
    ,@PageIndex int 
    ,@TotalRowsNumber int output
AS
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageSize + @PageLowerBound

--Default order by to first column
IF (@OrderBy is null or LEN(@OrderBy) < 1)
BEGIN
    SET @OrderBy = 'EmployeeID DESC'
END

-- SQL Server 2005 Paging
declare @SQL as nvarchar(4000)
declare @SQLCOUNT as nvarchar(4000)
declare @Param as nvarchar(500)

SET @SQL = 'WITH PageIndex AS ('
SET @SQL = @SQL + ' SELECT  '
IF @PageSize > 0
BEGIN
    SET @SQL = @SQL + ' TOP ' + convert(nvarchar, @PageUpperBound)
END

SET @SQL = @SQL + ' ROW_NUMBER() OVER (ORDER BY ' + @OrderBy + ') as RowIndex '
SET @SQL = @SQL + ' ,EmployeeID'
SET @SQL = @SQL + ', LastName'
SET @SQL = @SQL + ', FirstName'
SET @SQL = @SQL + ', Title'

SET @SQL = @SQL + ' FROM employees'
IF Len(@Search) > 0 
BEGIN
    SET @SQL = @SQL + ' ' + @Search
END
SET @SQL = @SQL  + ') SELECT '
SET @SQL = @SQL + ' EmployeeID'
SET @SQL = @SQL + ', LastName'
SET @SQL = @SQL + ', FirstName'
SET @SQL = @SQL + ', Title'
SET @SQL = @SQL + ' FROM PageIndex  '
SET @SQL = @SQL + ' WHERE RowIndex > ' + convert(nvarchar, @PageLowerBound)

IF @PageSize > 0
BEGIN
SET @SQL = @SQL + ' AND RowIndex <= ' + convert(nvarchar, @PageUpperBound)
END

--Get Row Count
SET @SQLCOUNT = 'SELECT @TotalRowsNumber  = count(EmployeeID)
                    FROM employees' 
SET @Param = N'@Search nvarchar(2000),@TotalRowsNumber INT OUTPUT'
IF LEN(@Search) > 0
BEGIN
    SET @SQLCOUNT = @SQLCOUNT + @Search 
END
exec sp_executesql @SQL
exec sp_executesql @SQLCOUNT, @Param,@Search=@Search,@TotalRowsNumber = @TotalRowsNumber OUT

提前致谢!

4

1 回答 1

1

试试这样,看它的例子

CREATE Procedure usp_GetBookings
@pageIndex int,
@pageSize tinyint
as
;with CTE as 
(
Select Distinct ROW_NUMBER() over( order by ssi.SSItineraryID desc) as seq ,Count(*) over() as TotalRow,ssi.SSItineraryID 
 from SightSeeingItinerary as ssi
)

select * from CTE
where cte.seq  between  (@pageIndex-1) * @pageSize+1 and ((@pageIndex-1) * @pageSize +(@pageSize))
于 2013-05-30T08:49:27.110 回答