How can I reuse a Common Table Expression

后端 未结 3 1306
迷失自我
迷失自我 2020-12-16 09:41

I am using a Common Table Expression for paging:

with query as (
  Select Row_Number() over (Order By OrderNum ASC) as TableRowNum,
         FirstName,
              


        
3条回答
  •  执念已碎
    2020-12-16 10:22

    According to Microsoft in this link:

    A CTE can reference itself and previously defined CTEs in the same WITH clause.

    In that new CTE referencing the previous defined CTE, we can make the count query:

    ;with query as (
      Select Row_Number() over (Order By UserID ASC) as TableRowNum,
             FirstName,
             LastName
      From   Users
    ),
    totalCount AS (
        SELECT COUNT(1) Total FROM query
    )
    Select  query.*,
            Total
    from    query, totalCount 
    where   TableRowNum 
    between 1 and 25 
    Order By TableRowNum ASC
    

    'query' is the main CTE and 'totalCount' is using it for get the total rows count

    Microsoft should have an example for a common task like this.

提交回复
热议问题