2017-06-02 146 views
0

我试图在from子句中使用递归CTE。这CTE作品本身:DB2子查询中的CTE

with i (i) as ( 
    values (1) 
    union all 
    select i + 1 from i 
    where i < 3 
) 
select * from i; 

      I 
------------- 
      1 
      2 
      3 

但是当我尝试它from子句中:

select * 
from (
    with i (i) as ( 
     values (1) 
     union all 
     select i + 1 from i 
     where i < 3 
    ) 
    select * from i 
) i; 
ERRO próximo da linha 1: 
SQL0104N An unexpected token "as" was found following "* 
from (
with i (i)". Expected tokens may include: "JOIN". 

类似的结构在PostgreSQL工作。我错过了什么?

+0

为什么你需要一个CTE的'FROM'子句中?看起来像是一个X-Y问题。正如您所看到的,它在DB2中的语法不正确(并且在语义上是不必要的)。 – mustaccio

+0

@mustaccio它也可能是选择列表中的相关子查询,但我认为它在横向连接中会更干净。我现在无法测试相关的子查询。它合法吗? –

回答

1

喜“与”语句必须先在DB2查询,试试这个

with i (i) as (
    values (1) 
    union all 
    select i + 1 from i 
    where i < 3 
) 
select * 
    from (

      select * from i 
     ) i;