如何重用公用表表达式

时间:2009-11-26 06:58:19

标签: sql sql-server common-table-expression

我使用公用表表达式进行分页:

with query as (
  Select Row_Number() over (Order By OrderNum ASC) as TableRowNum,
         FirstName,
         LastName
  From   Users
)
Select * from query where TableRowNum between 1 and 25 Order By TableRowNum ASC

在进行此查询后,我立即进行几乎相同的查询以检索项目总数:

with query as (
  Select Row_Number() over (Order By OrderNum ASC) as TableRowNum,
         FirstName,
         LastName
  From   Users
)
Select Count(*) from query

我尝试将这些组合在一起(即:定义CTE,查询数据然后查询Count,但是当我这样做时,我收到错误消息“无效对象名称'查询'”以响应第二个查询(伯爵)。

有没有办法将这两个查询合并为一个,以保存到DB的往返?

3 个答案:

答案 0 :(得分:35)

如果您在2个不同的查询中不需要它们,可以尝试

;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

如果确实需要2个不同的查询,请使用表格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

答案 1 :(得分:2)

你可以这样做:

with query as (
   Select 
 COUNT (*) OVER (PARTITION BY 1) AS TableTotalRows,
 Row_Number() over (Order By OrderNum ASC) as TableRowNum,
     FirstName,
     LastName
  From   Users
)

答案 2 :(得分:2)

根据微软的link

  

CTE可以引用自身和之前定义的CTE   WITH子句。

在引用先前定义的CTE的新CTE中,我们可以进行计数查询:

;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'是主CTE,'totalCount'用它来获取总行数

微软应该有一个像这样的常见任务的例子。