Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Multiple CTE

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

like image 818
paparazzo Avatar asked Sep 20 '13 19:09

paparazzo


People also ask

Can you use multiple CTE?

Having Multiple CTEs work only if you write the WITH keyword once. But this is not just anywhere you want. You have to write it before the first CTE. The second and any following CTE starts with the name of the respective CTEs, unlike the first CTE which starts with the WITH keyword.

Can I use CTE in another CTE?

A CTE name can be referenced in other CTEs, enabling CTEs to be defined based on other CTEs. A CTE can refer to itself to define a recursive CTE. Common applications of recursive CTEs include series generation and traversal of hierarchical or tree-structured data.

Does using CTE improve performance?

Below is the T-SQL for each of our test query types. Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.


1 Answers

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])
like image 137
podiluska Avatar answered Oct 07 '22 19:10

podiluska