9

无法弄清楚如何使用多个 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() 分区
我刚刚使用派生表

4

1 回答 1

10

第一个失败是因为一个 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])
于 2013-09-20T20:23:34.890 回答