I'm wondering whether such query could be potentially optimized. I've hugely simplified it, and you see the core of it.
with Rec (Id,Name,ParentId)
as
(
select Id,Name,ParentId from Departments where ParentId is null
union all
select d.Id, d.Name, d.ParentId from Departments d join Rec r on
(d.ParentId=r.Id)
)
select q.* from (
select ROW_NUMBER() OVER (ORDER BY r.Id DESC) AS [ROW_NUMBER], r.* from Rec r
) as q
where q.[ROW_NUMBER] between 100 and 200
What it does is hierarchically query the desendent departments and then do a ranging upon it.
I'm ending up with a huge execution plan and wondering if it can be done in a different manner.
Thank you.