クエリを 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
前もって感謝します!