web-dev-qa-db-ja.com

SQL Server WITHステートメント

私の目標は、1つのCTEから結果を選択し、同じ手順で別のCTEを使用して他のテーブルに挿入することです。どうやってするの?

私のエラーは...

無効なオブジェクト名xy。

私のクエリは

WITH ds
(
    Select a, b, c 
    from test1    
),
xy
(
    select d, e, f 
    from test2 
    where (uses conditions from ds)    
)
Select * 
from ds  (the result set of ds, am exporting this to csv)

Insert into AuditTest
(
  Select * from xy
)
7
user28455

CTEは1つのクエリに対してのみ有効ですが、各クエリでCTEを使用できるようです。

WITH ds AS
(
  Select a, b, c from test1    
)
Select * from ds  (the result set of ds, am exporting this to csv)


WITH xy AS
(
 select d,e,f from test2 where (uses conditions from test1)    
)
Insert into AuditTest
(
  Select * from xy
)
13
D Stanley

実際には、OUTPUT句を使用して挿入と出力の両方を実行し、挿入された行を返すことができます。

;WITH ds AS
(
  Select a, b, c from test1 
),
xy AS
(
 select d, e, f from test2 where (uses conditions from ds)
)
Insert into AuditTest
output inserted.d, inserted.e, inserted.f
Select d, e, f from xy

または実際のテスト

CREATE TABLE #Test (a int)

;WITH ds AS
(
  Select 0 as a, 1 as b, 2 as c 
),
xy AS
(
 select a as d, b as e from ds
)
Insert into #Test 
OUTPUT inserted.a
Select e from xy
5
Ceres

したがって、INSERTを実行できます。cteの後に複数のクエリを実行することはできません。

;WITH ds AS (  Select a, b, c 
              from test1    
           )
    ,xy AS (  select d,e,f 
              from test2 
              where (uses conditions from test1)    
           )
Insert into AuditTest
Select * 
from xy

この状況では、一時テーブルを使用すると、クエリを複数回再実行するため、有益な場合があります。

0
Hart CO