2016-04-05 2 views
0

複数のSQL selectクエリを持つ構造体を使用したいと思います。例:最初の選択クエリが実行された後、しかし構造体で - "with"を繰り返さずに複数のselectクエリを使用する

;with temptable as (...) 
select id from temptable 
select name from temptable 

SQL Server 2008 doesntのは、私はそれを行うことができ、それが2番目のクエリの上に再び構造と同じことを書くために私をプッシュします。例:

;with temptable as (...) 
select id from temptable 
;with temptable as (...) 
select name from temptable 

最初の選択クエリの後にカンマを使用しようとしましたが、動作しませんでした。 SQL Server 2008の構造で複数の選択クエリを使用するにはどうすればよいですか。

+1

'SELECT .... FROM #temptable INTO'し、次いで '#temptableからIDを選択します。 名前を#temptableから選択してください;あなたの場合に役立ちますか? – lad2025

+0

あなたはそれをどうしたいのかの例を追加できますか?どのような種類のデータを照会するのか、また、望ましい結果は何ですか? – Jeffrey

+0

なぜあなたは単一のクエリ 'SELECT id、name FROM temptable'を望んでいませんか?なぜあなたはIDと異なる順序で名前を取得する危険がありますか? –

答えて

2

Common table expressionは、1つのステートメントに対してのみ機能します。

共通テーブル 式(CTE)と呼ばれる一時的な名前付き結果セットを指定します。これは単純なクエリから導出され、のSELECT、INSERT、UPDATEまたは DELETEステートメントの実行スコープ内に と定義されています。

select id from temptable; 
select name from temptable; 

は二つの文ですので、あなたは、2番目のクエリでそれを使用することはできません。

代替一時テーブルを使用することである:...

SELECT .... INTO #temptable FROM ...; -- your query from CTE 
SELECT id FROM #temptable; 
SELECT name FROM #temptable; 
0
 
CTE only exists for the "duration of the query" you can't use the same CTE in two different SELECT statements as each is a separate query. 
you need to store the result set of CTE into temp table to and fire multiple select statements on temp table. 

;with temptable as (...) 
select id 
into #tempResultSet 
from temptable 

select name from tempResultSet 
関連する問題