---
title: "Oracle--递归"
author: "keepwork"
date: "2013-12-23T21:01:25Z"
tags: []
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2014-04-07T00:22:10Z"
id: 1994104
url: "https://keepwork.iteye.com/blog/1994104"
---

**开发者博客：[www.developsearch.com](http://www.developsearch.com "开发者博客")**

 

 

**CONNECT BY 递归查询树形结构关系**

命令格式如下：  
SELECT ….. CONNECT BY {PRIOR 列名1=列名2|列名1=PRIOR 列名2}  
\[START WITH]；  
其中：CONNECT BY子句说明每行资料将是按层次顺序检索，并规定将表中的资料连入树形结构的关系中。  
0PRIORY运算符必须放置在连接关系的两列中的某一个的前面。对于节点间的父子关系，PRIOR去处符在一侧表示父节点，  
在别一侧表示子节点，从而确定查找权结构的顺序是自顶向下还是自底向上。在连接关系中，除了可以使用列名外，  
还允许使用列运算式。START WITH 子句为可选项，用来标识哪个节点作为查找树型结构的根节点。  
**例子：**

从Root往树末梢递归 

```
select * from TBL_TEST
 start with id=1
 connect by prior id = pid
```

 从末梢往树ROOT递归

```
select * from TBL_TEST
 start with id=5
 connect by prior pid = id
```

可通过level 关键字查询所在层次 

```
select a.*,level from TBL_TEST
start with id=1
 connect by prior id = pid 
```

通过子节点获得顶节点

```
select FIRST_VALUE(deptid) OVER (ORDER BY LEVEL DESC ROWS UNBOUNDED PRECEDING) AS firstdeptid 
from persons.dept start with deptid=76 connect by prior paredeptid=deptid  
```

**下拉中用数据源取年份时，可用如下方式写：**  
select * from  
(select rownum,to\_char(add\_months(sysdate, 4), 'yyyy') - rownum  
from dual connect by rownum&lt;5);

 

**递归删除树节点**

```
/**
	 * 递归删除所有子节点
	 */
	public void removeNode(Long areaId){
        List<Object> args = new ArrayList<Object>();
        args.add(areaId);
        
		StringBuffer sql = new StringBuffer("");
		sql.append(" delete from CDH_NEWRBT_AREA t where t.area_id in ");
		sql.append(" ( ");
		sql.append(" 	select a.area_id from CDH_NEWRBT_AREA a ");
		sql.append(" 	start with a.area_id = ? ");
		sql.append(" 	connect by prior  a.area_id = a.parent_id");
		sql.append(" ) ");
		log.info(sql.toString());
        
        this.executeUpdateSql(sql.toString(), args);
    }
	
	public int executeUpdateSql(final String sql, final List<Object> args){
        return (Integer)getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(sql);
                if (args != null && args.size() > 0) {
                    Object[] values = args.toArray();
                    for (int i = 0; i < values.length; i++) {
                        query.setParameter(i, values[i]);
                    }
                }                
                return query.executeUpdate();
            }
        });    
    }
```

 

 

 

oracle : 

 

        select t.organization\_id from ims\_rt\_organization t

       connect by prior t.organization\_id = t.super\_organization\_id

                start with t.super\_organization\_id=#value#

 

        //得到本组织所有的上级组织ID

        select t.super\_organization\_id from ims\_rt\_organization t

                 connect by prior t.super\_organization\_id = t.organization\_id

                  start with t.organization\_id=#value#

 

 

db2 :

with b(organization\_id) as (

             select organization\_id

                from ims\_rt\_organization where  organization\_id = #value#

         union all

             select a.organization\_id

                 from ims\_rt\_organization as a,b

              where b.organization\_id = a.super\_organization\_id )

select * from b

 

**开发者博客：[www.developsearch.com](http://www.developsearch.com "开发者博客")**