I have a huge sql query with multiple joins and bundle of where conditions (filters). The query returns results with pagination or page wise. Now in other case I need only a total count as result instead of records list based on same applied filters. One way is to repeat/copy the same query and changing the SELECT clause plus removing the pagination OFFSET @PageSize * (@PageIndex - 1) ROWS FETCH NEXT @PageSize ROWS ONLY and all the WHERE conditions would be repeated, so in future if there's any change I have to change both queries. Is there any way around to reuse all the WHERE conditions since only the selection is being changed?
First query:
SELECT Id,Name
FROM Users
WHERE 1=1
...bundle of where conditions
ORDER BY Name
OFFSET @PageSize * (@PageIndex - 1) ROWS FETCH NEXT @PageSize ROWS ONLY
Second query:
SELECT COUNT(1)
FROM Users
WHERE 1=1
...reuse above bundle of where conditions