是否可以将具有相同结构的两个CTE的结果集联合起来

时间:2010-09-10 14:51:12

标签: sql-server-2005

我想结合以下CTE的结果集,以便获得4行数据。

Id  Name
-------------
1    Test1  
2   Test2  
3   Test3  
4   Test4

我想使用的Sql如下

;with CTE1 (Id,Name)
as
( 
    select 1 as Id, 'Test1' as Name
    union all
    select 2, 'Test2'
)
select * from CTE1
union all
;with CTE2 (Id,Name)
as
( 
    select 3 as Id, 'Test3' as Name
    union all
    select 4, 'Test4'
)
select * from CTE2

但是,我收到语法错误,提示我不能在两个CTE之间使用Union All。 我怎么能绕过这个?

3 个答案:

答案 0 :(得分:1)

是的,但不是你这样做的方式。试试这种方式:

;with CTE1 (Id,Name)
as
( 
    select 1 as Id, 'Test1' as Name
    union all
    select 2, 'Test2'
)
,CTE2 (Id,Name)
as
( 
    select 3 as Id, 'Test3' as Name
    union all
    select 4, 'Test4'
)
select * from CTE1
union all
select * from CTE2

您可以将多个CTE链接在一起。 CTE之间只有一个“WITH”和一个逗号。然后在CTE之后的陈述中,您可以引用任何这些CTE。

答案 1 :(得分:1)

;with CTE1 (Id,Name) 
as 
(  
    select 1 as Id, 'Test1' as Name 
    union all 
    select 2, 'Test2' 
) 
,CTE2 (Id,Name) 
as 
(  
    select 3 as Id, 'Test3' as Name 
    union all 
    select 4, 'Test4' 
) 
select * from CTE1
union all
select * from CTE2 

答案 2 :(得分:0)

with CTE1 (Id,Name)
as
( 
    select 1 as Id, 'Test1' as Name
    union all
    select 2, 'Test2'
),
CTE2 (Id,Name)
as
( 
    select * from CTE1
    union all
    select 3 as Id, 'Test3' as Name
    union all
    select 4, 'Test4'
)
select * from CTE2

with CTE1 (Id,Name)
as
( 
    select 1 as Id, 'Test1' as Name
    union all
    select 2, 'Test2'
),
CTE2 (Id,Name)
as
( 
    select 3 as Id, 'Test3' as Name
    union all
    select 4, 'Test4'
)
select * from CTE1
union all
select * from CTE2