如何在db2中使用递归查询

时间:2016-05-10 13:12:06

标签: sql db2

我正在学习在db2中使用递归查询,在网上遇到问题打印以下模式

 * 
 ** 
 *** 
 **** 
 ***** 
 ****** 
 ******* 
 ******** 
 ********* 
 ********** 
 *********** 

高达20级,使用以下查询在Oracle中解决了它

select lpad('*', level, '*') result  from dual  connect by level <= 20 

但不知道如何在db2中这样做,真的很感激任何帮助。

另外,如何以相反的顺序进行操作,意味着如何从20级到1级打印星形金字塔?

3 个答案:

答案 0 :(得分:0)

dual替换为sysibm.sysdummy1

select lpad('*', level, '*') result  
from sysibm.sysdummy1   
connect by level <= 20                                                           

答案 1 :(得分:0)

用于打印1到20 * s

的递归查询
with x(id,val) as 
(
   select 1 as id,lpad('*',1,'*') as val from sysibm.sysdummy1
   union all
   select id+1,lpad('*',id+1,'*') from x where id < 20
)
select val from x

递归查询打印20到1 * s

with x(id,val) as 
(
 select lpad('*',20,'*') as val,20 as id from sysibm.sysdummy1
 union all
 select lpad('*',id-1,'*'),id-1 from x where id > 1
)
select val from x

答案 2 :(得分:0)

使用REPEAT代替LPAD

更正db2的查询
with x(id,val) as 
(
 select 1, REPEAT('*',1) from sysibm.sysdummy1
 union all
 select id+1, REPEAT('*',id+1) from x where id < 20
)
select val from x

with x(id,val) as 
(
 select 20, REPEAT('*',20) from sysibm.sysdummy1
 union all
 select id-1, REPEAT('*',id-1) from x where id > 1
)
select val from x