create table A
(
DEPTID INTEGER not null, --部门ID
DEPT_CODE VARCHAR2(720) not null, --部门编码
PARENT_ID VARCHAR2(720) not Null --父节点('-1'为顶级节点,'-'1的下级节点为一级部门)
);
alter table A add constraint DEPT_CODE_PK primary key (DEPT_CODE);
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('1004', '106707000000', '281' );
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('281' , '106700000000', '43' );
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('43' , '100000000000', '7289');
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('7289', '000000000000', '-1' );
Commit;
--查找当前编码的一级部门
With all_id As (
Select t.parent_id , t.deptid From A t
Start With t.dept_code = '106707000000'
Connect By Prior t.parent_id = t.deptid )
Select deptid From all_id a Where a.parent_id =
(Select b.deptid From all_id b Where b.parent_id = '-1')
(
DEPTID INTEGER not null, --部门ID
DEPT_CODE VARCHAR2(720) not null, --部门编码
PARENT_ID VARCHAR2(720) not Null --父节点('-1'为顶级节点,'-'1的下级节点为一级部门)
);
alter table A add constraint DEPT_CODE_PK primary key (DEPT_CODE);
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('1004', '106707000000', '281' );
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('281' , '106700000000', '43' );
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('43' , '100000000000', '7289');
Insert Into A (DEPTID,DEPT_CODE,PARENT_ID) Values('7289', '000000000000', '-1' );
Commit;
--查找当前编码的一级部门
With all_id As (
Select t.parent_id , t.deptid From A t
Start With t.dept_code = '106707000000'
Connect By Prior t.parent_id = t.deptid )
Select deptid From all_id a Where a.parent_id =
(Select b.deptid From all_id b Where b.parent_id = '-1')
构建部门层级结构
本文介绍了一个使用SQL创建部门层级结构的过程。首先定义了一个包含部门ID、编码和父节点的表,并设置了主键约束。接着通过插入几条记录来构建一个具体的部门层级实例,并通过WITH语句实现了对指定部门编码的一级部门进行查询。
1335

被折叠的 条评论
为什么被折叠?



