使用多个CTE

时间:2013-09-20 19:50:19

标签: sql-server tsql common-table-expression

无法弄清楚如何使用多个CTE

这失败

; with [cteOne] as (
  select 1 as col
),
  [cteTwo]  as (
  select 2 as col
)
select 'yesA' where exists (select * from [cteOne])
select 'yexB' where exists (select * from [cteTwo])

这有效 - 但这不是我需要的

; with [cteOne] as (
  select 1 as col
),
  [cteTwo]  as (
  select 2 as col
)
select * from [cteOne]
union 
select * from [cteTwo]

真正的语法是row_number()分区的连接
我刚刚结束使用派生表

1 个答案:

答案 0 :(得分:9)

第一个失败是因为CTE或一组CTE后面只能跟一个语句。

您可以将其重写为

; with [cteOne] as (
  select 1 as col
)
select 'yesA' where exists (select * from [cteOne])

; with [cteTwo]  as (
  select 2 as col
)
select 'yexB' where exists (select * from [cteTwo])