oracle递归查询使用

转自: Oracle “CONNECT BY” 使用

-- Create table
create table DEP
(
  DEPID      number(10) not null,
  DEPNAME    varchar2(256),
  UPPERDEPID number(10)
);


SQL> INSERT INTO DEP(DEPID, DEPNAME, UPPERDEPID) VALUES (0, '总经办', null);
1 row inserted
 
SQL> INSERT INTO DEP(DEPID, DEPNAME, UPPERDEPID) VALUES (1, '开发部', 0);
1 row inserted
 
SQL> INSERT INTO DEP(DEPID, DEPNAME, UPPERDEPID) VALUES (2, '测试部', 0);
1 row inserted
 
SQL> INSERT INTO DEP(DEPID, DEPNAME, UPPERDEPID) VALUES (3, 'Sever开发部', 1);
1 row inserted
 
SQL> INSERT INTO DEP(DEPID, DEPNAME, UPPERDEPID) VALUES (4, 'Client开发部', 1);
1 row inserted
 
SQL> INSERT INTO DEP(DEPID, DEPNAME, UPPERDEPID) VALUES (5, 'TA测试部', 2);
1 row inserted
 
SQL> INSERT INTO DEP(DEPID, DEPNAME, UPPERDEPID) VALUES (6, '项目测试部', 2);
1 row inserted
 
SQL> commit;
Commit complete


SQL> SELECT RPAD( ' ', 2*(LEVEL-1), '-' ) || DEPNAME "DEPNAME",
CONNECT_BY_ROOT DEPNAME "ROOT",
CONNECT_BY_ISLEAF "ISLEAF",
LEVEL ,
SYS_CONNECT_BY_PATH(DEPNAME, '/') "PATH"
FROM DEP
START WITH UPPERDEPID IS NULL
CONNECT BY PRIOR DEPID = UPPERDEPID;
 
DEPNAME                        ROOT                    ISLEAF      LEVEL PATH
------------------------------ ------------------- ---------- ---------- --------------------------------------------------------------------------------
General Deparment              General Deparment            0          1 /General Deparment
 -Development                  General Deparment            0          2 /General Deparment/Development
 ---Server Development         General Deparment            1          3 /General Deparment/Development/Server Development
 ---Client Development         General Deparment            1          3 /General Deparment/Development/Client Development
 -QA                           General Deparment            0          2 /General Deparment/QA
 ---TA                         General Deparment            1          3 /General Deparment/QA/TA
 ---Porject QA                 General Deparment            1          3 /General Deparment/QA/Porject QA
                                                    
7 rows selected


说明: 
1. CONNECT_BY_ROOT 返回当前节点的最顶端节点 
2. CONNECT_BY_ISLEAF 判断是否为叶子节点,如果这个节点下面有子节点,则不为叶子节点 
3. LEVEL 伪列表示节点深度 
4. SYS_CONNECT_BY_PATH函数显示详细路径,并用“/”分隔


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值