oracle 递归
可以结合树,通过节点层次,跟是否是叶子节点配合展示树。
LEVEL:查询节点层次,从1开始。 CONNECT_BY_ISLEAF:查询节点是否是叶子节点,是则为1,不是则为0 SELECT ID, NAME, PARENT_ID, LEVEL, CONNECT_BY_ISLEAF FROM SC_DISTRICT START WITH NAME='巴中市' CONNECT BY PRIOR ID=PARENT_ID ORDER BY ID; 查询结果: ID NAME PARENT_ID LEVEL CONNECT_BY_ISLEAF 2 巴中市 1 1 0 4 巴州区 2 2 1 5 通江县 2 2 1 6 平昌县 2 2 0 13 大寨乡 6 3 1 14 响滩镇 6 3 1 15 龙岗镇 6 3 1 16 白衣镇 6 3 1
递归拼接字符串
select sys_connect_by_path(ename,'>') tree from emp start with ename='King' connect by prior empno = mgr;
需求:组织机构表t_uic_dept, dept_level = 2为公司,dept_level='5'为部门。
现在要查出所有部门以及对应的公司一行展示。
展示列为:部门Code,部门名称,公司Code,公司名称。
SQL为:
with a as
(select t.dept_code, t.dept_name, t.dept_level, t.dept_parentcode
from caissa_erp_uic.T_UIC_DEPT t
where t.dept_level = '5'),
b as
(select d.dept_code,
d.dept_name,
d.dept_level,
sys_connect_by_path(d.dept_code, '/') treepath
from caissa_erp_uic.T_UIC_DEPT d
where d.dept_level = '2'
CONNECT BY NOCYCLE PRIOR d.dept_parentcode = d.dept_code
start with d.dept_code in (select a.dept_code from a))
select a.dept_code,
a.dept_name,
-- a.dept_level,
b.dept_code,
b.dept_name
-- b.dept_level
from a, b
where instr(b.treepath, a.dept_code) > 0