不能两次使用WITH语句

时间:2017-05-02 09:24:38

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

我不想创建一个像这样构建的视图: (简化的)

Create VIEW viewAll AS
With TempLevel1 AS

SELECT statement

With TempLevel2 AS (SELECT * from TempLevel1)

SELECT * from TempLevel2

问题是因为我不能使用这样的With语句 以下错误:

  

关键字附近的语法错误'使用'。   关键字'附近的语法不正确,用'。

     

如果这个陈述是   公用表表达式,xmlnamespaces子句或更改跟踪   context子句,前一个语句必须以a结尾   分号。

我必须指定SELECT查询更复杂,我必须使用两次。

更好的做法是将第一个with语句创建为另一个视图,如viewTempLevel1(并在With TempLevel2语句中使用它)?

2 个答案:

答案 0 :(得分:4)

从公共表格表达式的documentation CTE ),您可以

  

使用逗号分隔多个CTE定义

示例(直接取自文档)

WITH Sales_CTE (SalesPersonID, TotalSales, SalesYear)  
AS  
-- Define the first CTE query.  
(  
    SELECT SalesPersonID, SUM(TotalDue) AS TotalSales, YEAR(OrderDate) AS SalesYear  
    FROM Sales.SalesOrderHeader  
    WHERE SalesPersonID IS NOT NULL  
       GROUP BY SalesPersonID, YEAR(OrderDate)  

)  
,   -- Use a comma to separate multiple CTE definitions.  

-- Define the second CTE query, which returns sales quota data by year for each sales person.  
Sales_Quota_CTE (BusinessEntityID, SalesQuota, SalesQuotaYear)  
AS  
(  
       SELECT BusinessEntityID, SUM(SalesQuota)AS SalesQuota, YEAR(QuotaDate) AS SalesQuotaYear  
       FROM Sales.SalesPersonQuotaHistory  
       GROUP BY BusinessEntityID, YEAR(QuotaDate)  
)  

-- Define the outer query by referencing columns from both CTEs.  
SELECT SalesPersonID... 

在您的情况下,语法将是......

With TempLevel1 AS
    ( SELECT statement [...]), 
TempLevel2 AS 
    (SELECT * from TempLevel1)

SELECT * from TempLevel2

答案 1 :(得分:3)

您不需要重复WITH关键字。用逗号分隔CTE表达式:

With CTE_Level1 AS
( 
    SELECT statement 
),
CTE_Level2 AS 
(
    SELECT * from CTE_Level1
)
SELECT * from CTE_Level2