SQL Server WITH语句

25

我的目标是在同一个存储过程中从一个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
)

我现在编辑了我的问题。Xy使用DS中的条件。如果我使用两个with语句,它仍然会给我同样的错误。 - user28455
1
CTE是单个SQL语句的一部分。错误“无效对象名称xy”来自您的第二个语句,即INSERT语句,该语句没有定义任何CTE。(第一个语句是SELECT,作为语句的一部分定义了两个CTE。)要使第二个语句使用CTE,这些将需要包含在第二个语句中。 - spencer7593
3个回答

25

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
)

7
您可以使用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

3

你可以这样运行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

在这种情况下,使用临时表可能是有益的,因为否则您将多次重新运行查询。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接