如何为递归sql设置停止条件?

时间:2016-04-05 02:09:21

标签: sql database recursion db2 recursive-query

Page

这是无限运行的,因为数据中有循环,有没有办法在这个语句中添加一个停止条件,所以如果该行已经存在于闭包中,我希望它停止该行的递归。

2 个答案:

答案 0 :(得分:1)

这个例子将循环限制为100 - 我想你明白了:

with closure (obj_1, obj_2, counter) as (
 SELECT distinct t.obj_1, t.obj_2 , 1 
   FROM temp4 t
 UNION ALL 
 SELECT c.obj_1, t.obj_2, counter + 1 
   FROM closure c, temp4 t 
  WHERE c.obj_2=t.obj_1
    AND counter <= 100)
SELECT * FROM closure

答案 1 :(得分:0)

最简单的方法是建立一个查询助手,类似这样的

with closure (obj_1, obj_2) as (
 SELECT distinct t.obj_1, t.obj_2,convert(varchar(30),t.obj_1)+';' as treePath
   FROM temp4 t
 UNION ALL 
 SELECT c.obj_1, t.obj_2 convert(varchar(30),t.obj_2)+';' as treePath
   FROM closure c, temp4 t
   WHERE c.obj_2=t.obj_1
and charindex(';' + convert(varchar(30),t.obj_2)+';',treepath,1)=0
SELECT * FROM closure