使用多个CTE

pap*_*zzo 8 t-sql sql-server 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])
Run Code Online (Sandbox Code Playgroud)

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

; with [cteOne] as (
  select 1 as col
),
  [cteTwo]  as (
  select 2 as col
)
select * from [cteOne]
union 
select * from [cteTwo]
Run Code Online (Sandbox Code Playgroud)

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

pod*_*ska 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])
Run Code Online (Sandbox Code Playgroud)

  • @Drewdin技术上不是这样.但是在前一个语句之后需要有一个分号,与许多其他语句不同,所以在with之前使用分号确保如果你不习惯使用分号分隔符. (2认同)