私の目標は、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
)
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
)
実際には、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
したがって、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
この状況では、一時テーブルを使用すると、クエリを複数回再実行するため、有益な場合があります。