I want to make a database query with pagination. So, I used a common-table expression and a ranked function to achieve this. Look at the example below.
decla
What if you calculate the count beforehand?
declare @pagenumber int = 2;
declare @pagesize int = 3;
declare @total int;
SELECT @total = count(*)
FROM @table
with query as
(
select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line from @table
)
select top (@pagesize) name, @total total from query
where line > (@pagenumber - 1) * @pagesize
Another way, is to calculate max(line). Check the link
Return total records from SQL Server when using ROW_NUMBER
UPD:
For single query, check marc_s's answer on the link above.
with query as
(
select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line from @table
)
select top (@pagesize) name,
(SELECT MAX(line) FROM query) AS total
from query
where line > (@pagenumber - 1) * @pagesize