Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With clause not working with union

Tags:

oracle

My query result is a union of several queries. I am facing the below error when I use WITH clause within a union. Any ideas why?

select column1 from TABLE_A
union
with abcd as (select * from TABLE_B)
    select column2 from TABLE_A A, abcd 
    where abcd.m_reference = A.m_reference

ORA-32034: unsupported use of WITH clause
32034. 00000 - "unsupported use of WITH clause"
*Cause: Inproper use of WITH clause because one of the following two reasons
1. nesting of WITH clause within WITH clause not supported yet
2. For a set query, WITH clause can't be specified for a branch.
3. WITH clause can't sepecified within parentheses.
*Action: correct query and retry

like image 877
asb Avatar asked Apr 07 '17 06:04

asb


2 Answers

Encapsulate your WITH statement in a dummy select.

select column1 from TABLE_A
union
select * from (
  with abcd as (select * from TABLE_B)
    select column2 from TABLE_A A, abcd 
    where abcd.m_reference = A.m_reference
)
like image 89
Rudolf van Elmpt Avatar answered Nov 03 '22 18:11

Rudolf van Elmpt


Just define the CTE first, before the actual UNION query. Then use it as you would a regular table:

with abcd as (select * from TABLE_B)
select column1 from TABLE_A
union
select column2
from TABLE_A A
inner join abcd
    on abcd.m_reference = A.m_reference

You can use multiple CTE as follows:

with cte1 AS (...),
     cte2 AS (...)
select * from ...
like image 8
Tim Biegeleisen Avatar answered Nov 03 '22 19:11

Tim Biegeleisen