2013-07-19 57 views
-1

我想在查詢中使用多個CTE,但是我一直無法使其工作。以下是我想要做的示例:在一個聲明中使用多個CTE

WITH tbl1 AS 
    (SELECT * 
    FROM tblStuff) 

WITH tbl2 AS 
    (SELECT tbl1.fldStuff1 ... 
    FROM tbl1, tblStuff2) 

    SELECT * 
    FROM tbl2 
+0

礦山在你的時間之前加蓋了時間嗎?今天爲什麼這麼生氣@AaronBertrand?你比這更好:( – Meff

回答

8
WITH tbl1 AS 
    (SELECT * 
    FROM tblStuff), 

tbl2 AS 
    (SELECT tbl1.fldStuff1, tbl1.fldStuff2, tblStuff2.fldStuff1, tblStuff2.fldStuff2 
    FROM tbl1, tblStuff2) 

    SELECT * 
    FROM tbl2 

如果使用多個熱膨脹係數,不需要額外的WITH,單獨用逗號。

+3

-1對於沒有用';'結束你的陳述[參考](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/09/03/ladies-and-紳士,開始你的semi-colons.aspx) – Kermit

+0

+1,用於引用Aaron的博客爲此 – Meff

+2

是的,他很聰明 – Kermit

14

您只需指定WITH一次。然後,您可以列出用逗號分隔的其他CTE。例如: -

WITH cte1 AS 
(
    ... 
), 
cte2 AS 
(
    ... 
) 
SELECT ...;