101

私は複雑な選択ステートメントを単純化する過程にあるので、一般的なテーブル式を使用すると考えました。

単一の cte を宣言すると正常に機能します。

WITH cte1 AS (
    SELECT * from cdr.Location
    )

select * from cte1 

同じ SELECT で複数の cte を宣言して使用することは可能ですか?

つまり、このSQLはエラーを出します

WITH cte1 as (
    SELECT * from cdr.Location
)

WITH cte2 as (
    SELECT * from cdr.Location
)

select * from cte1    
union     
select * from cte2

エラーは

Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

注意。セミコロンを入れてみましたが、このエラーが発生しました

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

おそらく関係ありませんが、これは SQL 2008 に関するものです。

4

2 に答える 2

155

私はそれが次のようなものであるべきだと思います:

WITH 
    cte1 as (SELECT * from cdr.Location),
    cte2 as (SELECT * from cdr.Location)
select * from cte1 union select * from cte2

基本的に、WITHここでは単なる節であり、リストを取る他の節と同様に、"," が適切な区切り文字です。

于 2009-02-25T00:40:31.820 に答える
17

上記の答えは正しいです:

WITH 
    cte1 as (SELECT * from cdr.Location),
    cte2 as (SELECT * from cdr.Location)
select * from cte1 union select * from cte2

さらに、 cte2 の cte1 からクエリを実行することもできます。

WITH 
    cte1 as (SELECT * from cdr.Location),
    cte2 as (SELECT * from cte1 where val1 = val2)

select * from cte1 union select * from cte2

val1,val2表現の仮定にすぎません..

このブログも役立つことを願っています: http://iamfixed.blogspot.de/2017/11/common-table-expression-in-sql-with.html

于 2015-03-17T16:27:24.880 に答える