I explore a possibility of using Common Table Expression (CTE) instead of temporary table in data paging. But the problem is that it looks like I can reference CTE only once in my script.
I need to return data for a current page as well as the row count for entire selection. Here is my script:
with names(row_num, first_name, last_name)
as
(
select
row_num = row_number() over(order by last_name, first_name),
first_name,
last_name
from contacts
where last_name like 's%'
and first_name like 'm%'
)
select
row_num,
first_name,
last_name
from names
where row_num between 41 and 60 -- 3rd page
order by row_num
select count(*) from names
go
It selects 20 records, however it displays an error when it tries to execute select count(*):
Msg 208, Level 16, State 1, Line 24
Invalid object name 'names'.
If I try to swap these two queries, it does select count(*) but displays same message for the second query. That means that I can reference CTE only once I tried to play with ; but result is the same.