Use Multiple CTE

2019-02-13 05:28发布

问题:

Cannot figure out how to use multiple CTE

This fails

; 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])

This works - but this is not what I need

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

The real syntax was a join to row_number() partition
I just ended up using a derived table

回答1:

The first one fails because a CTE or set of CTEs can only be followed by a single statement.

You could rewrite it as

; 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])