Link to home
Start Free TrialLog in
Avatar of AbeSpain
AbeSpainFlag for United Kingdom of Great Britain and Northern Ireland

asked on

TSQL Assignining CTE column in to a variable

I am updating a number of old, slower paging recordsets to use code found at the following url - http://stackoverflow.com/questions/12352471/getting-total-row-count-from-offset-fetch-next

Everything seems to be working fine apart from once I have accessed a CTE, I am unable to access it again (to perform a Select the count of rows and assign it to a variable, maybe using a top 1 clause). The total rows that the original CTE query returns is store multiple times as a column but this as helpful as storing that count in a variable.

The basis of the code is below, it's the MaxRows that I want to bung in to a variable :

DECLARE 
    @PageSize INT = 10, 
    @PageNum  INT = 1;

WITH TempResult AS(
    SELECT ID, Name
    FROM Table
), TempCount AS (
    SELECT COUNT(*) AS MaxRows FROM TempResult
)
SELECT *
FROM TempResult, TempCount
ORDER BY TempResult.Name
    OFFSET (@PageNum-1)*@PageSize ROWS
    FETCH NEXT @PageSize ROWS ONLY

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AbeSpain

ASKER

The old query presented the total rows that was read first in to a variable, then the data containing the recordset that was paged through afterwards. It makes sense to offer this as a variable first when you want to offer a drop down to quick jump x number of pages.
Solution works.