How can I reuse a Common Table Expression

后端 未结 3 1295
迷失自我
迷失自我 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:25

    If you do not require them in 2 different queries, you can try

    ;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
    

    If you do require 2 different queries, rather use a table var

    DECLARE @User TABLE(
            TableRowNum INT,
            FirstName VARCHAR(50),
            LastName VARCHAR(50)
    )
    ;with query as (
      Select Row_Number() over (Order By UserID ASC) as TableRowNum,
             FirstName,
             LastName
      From   Users
    )
    INSERT INTO @User
    SELECT  TableRowNum,
            FirstName,
            LastName
    FROM    query
    
    SELECT  *
    FROM    @User
    where   TableRowNum 
    between 1 and 25 
    Order By TableRowNum ASC
    
    SELECT COUNT(1) FROM @User
    

提交回复
热议问题