2014-05-02 50 views
1

我想創建一個CTE,如下所示調用另一個CTE。但我得到這個錯誤:使用調用另一個CTE的CTE - 近語法錯誤;

Msg 102, Level 15, State 1, Line 54 Incorrect syntax near ';'.

我真的不知道問題是什麼。我檢查了一堆類似於我的&的其他問題,嘗試從這些解決方案,但它不會因爲某些原因工作。

With SEASONALITY_AVG_REVENUE 
(
    YearKey 
    ,Aggregation_Key 
    ,Yearly_Avg_Revenue 
) 
as 
(
    SELECT 
     ts.YearKey, 
     agg.Aggregation_Key, 
     Yearly_Avg_Revenue = AVG(agg.Revenue) 

    FROM 
     seasonality_custom.TIME_SERIES_INDEX ts 
     INNER JOIN seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg 
     ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX 
    GROUP BY 
     ts.YearKey, 
     agg.Aggregation_Key 
) 
, SEASONALITY_ALL_RECS 
(
    YearKey 
    ,Aggregation_Key 
    ,Revenue 
    ,Yearly_Avg_Revenue 
) 
as 
(
    SELECT 
     ts.YearKey, 
     agg.Aggregation_Key, 
     agg.Revenue, 
     Yearly_Avg_Revenue = savg.Yearly_Avg_Revenue 
    FROM 
     seasonality_custom.TIME_SERIES_INDEX ts 
     INNER JOIN seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg 
     ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX 
     INNER JOIN SEASONALITY_AVG_REVENUE savg 
     ON ts.YearKey = savg.YearKey and agg.Aggregation_Key = savg.Aggregation_Key 
); 

回答

2

你不能有一個with聲明,除非你按照它通過一些其他的說法,通常select但在許多數據庫updatedelete爲好。

您的陳述有多個CTE,但它沒有主查詢部分。該錯誤是在分號上,因爲這會終止查詢。

1

你真的需要一個在這裏CTE

; With SEASONALITY_AVG_REVENUE(YearKey, Aggregation_Key, Yearly_Avg_Revenue) 
AS 
(
SELECT ts.YearKey, 
     agg.Aggregation_Key, 
     Yearly_Avg_Revenue = AVG(agg.Revenue) 

FROM seasonality_custom.TIME_SERIES_INDEX ts INNER JOIN 
seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg 
ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX 
GROUP BY ts.YearKey, agg.Aggregation_Key 
) 

SELECT ts.YearKey, 
     agg.Aggregation_Key, 
     agg.Revenue, 
     Yearly_Avg_Revenue = savg.Yearly_Avg_Revenue 
FROM seasonality_custom.TIME_SERIES_INDEX ts 
INNER JOIN seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg 
ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX 
INNER JOIN SEASONALITY_AVG_REVENUE savg 
ON ts.YearKey = savg.YearKey and agg.Aggregation_Key = savg.Aggregation_Key 

或者

戈登提到CTE需要跟一個SELECT,UPDATE,DELETE語句。

使用您當前的查詢,您可以簡單地從第二個CTE中選擇最後一個,它也會返回相同的結果,但這將是一個不必要的步驟。像這樣的東西..

;WITH CTE1 (Col1, Col2) 
AS 
    (
    -- Some code here 
), 
CTE2 
AS 
    (
    -- Some code here 
) 
SELECT * FROM CTE2 
+0

';'應該去聲明的_end_,而不是開頭。 –

+0

CTE是SQL Server中僅有的兩種情況之一,它要求前面的語句以';'結尾,因此很多SQL開發人員習慣於用';'開始CTE的習慣,用' ;'在SQL開發人員中並不常見。因此,壞/怪異的習慣:) –

+0

堅持這種壞習慣會讓人們認爲關鍵字是'; with'並導致所有類型的奇怪問題,如[this](http://stackoverflow.com/questions/23078215/cte -in-從子句-的-SQL查詢)。即使微軟建議用';'來終止所有查詢(參見例如[here](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/09/03/ladies-and-gentlemen-start-your-semi- colons.aspx)) –