HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Select total number of records from common table expression

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
totalexpressionnumberrecordsselectfromcommontable

Problem

We are using common table expressions to temporarily save the search results.

WITH Results (
                 ------
                  )
  AS
    (
          select ---
        )

 SELECT * FROM Results 

        WHERE Results.RowNum BETWEEN @StartIndex + 1 AND @StartIndex + @MaxCount


Here i want to get the toatal number of records in the Results common table expression in a variable @RowCount. Is there any way to get it without using table variable or temp table.

Solution

No, because you can't mix assignments and result set generation

But what you can do is make the total row count into an extra column

WITH Results AS
(
    select
        ---,
        COUNT(*) OVER () AS TotalRowCount -- this
    ...
)
SELECT
   *
FROM 
   Results 
WHERE 
   Results.RowNum BETWEEN @StartIndex + 1 AND @StartIndex + @MaxCount

Code Snippets

WITH Results AS
(
    select
        ---,
        COUNT(*) OVER () AS TotalRowCount -- this
    ...
)
SELECT
   *
FROM 
   Results 
WHERE 
   Results.RowNum BETWEEN @StartIndex + 1 AND @StartIndex + @MaxCount

Context

StackExchange Database Administrators Q#16601, answer score: 4

Revisions (0)

No revisions yet.