0

クエリを 2 回実行する SQL サーバー 2005 でページングに問題があります (データと合計行を取得します)。Northwind データベースに基づく私のデモ proc。もう一度クエリなしで合計行を取得する方法を教えてください。

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 に答える