SQL Server WITH语句

use*_*455 6 sql stored-procedures sql-server-2008

我的目标是从一个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
)
Run Code Online (Sandbox Code Playgroud)

D S*_*ley 12

CTE仅适用于一个查询,但看起来您可以在每个查询中使用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
)
Run Code Online (Sandbox Code Playgroud)


Cer*_*res 5

实际上,您可以使用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
Run Code Online (Sandbox Code Playgroud)

或真实的测试

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
Run Code Online (Sandbox Code Playgroud)