I have requirement to get the total count of records along with paging. At present I am doing it as listed below in SQL Server 2012. This needs a separate query for getting count. Is there any improved way in SQL Server 2012?
ALTER PROCEDURE dbo.tpGetPageRecords
(
@OffSetRowNo INT,
@FetchRowNo INT,
@TotalCount INT OUT
)
AS
SELECT CSTNO, CSTABBR
FROM DBATABC
WHERE CSTABBR LIKE 'A%'
ORDER BY CSTNO
OFFSET ( @OffSetRowNo-1 ) * @FetchRowNo ROWS
FETCH NEXT @FetchRowNo ROWS ONLY
SET @TotalCount =
(SELECT COUNT(*)
FROM DBATABC
WHERE CSTABBR LIKE 'A%')
GO
If we're allowed to change the contract, you can have:
SELECT CSTNO, CSTABBR,COUNT(*) OVER () as TotalCount
FROM DBATABC
WHERE CSTABBR LIKE 'A%'
ORDER BY CSTNO
OFFSET ( @OffSetRowNo-1 ) * @FetchRowNo ROWS
FETCH NEXT @FetchRowNo ROWS ONLY
And now the total will be available as a separate column in the result set. Unfortunately, there's no way to assign this value to a variable in this same statement, so we can no longer provide it as an OUT
parameter.
This uses the OVER
clause (available since 2005) to allow an aggregate to be computed over the entire (unlimited) result set and without requiring GROUP
ing.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments