我这样在plsql中有一个表
PK_ID DEPT_ID SUB_DEPT_ID 1 1 3 2 1 4 3 1 5 4 3 6 5 3 …
分层查询可能在此处运行良好。
尝试在“for..loop”中使用如下所示的查询:
select dept_id, sub_dept_id, level from dept_subdept START WITH dept_id = 1 connect by prior sub_dept_id=dept_id order by level,sub_dept_id;
例如...
GIVEN:包含以下数据的表DEPT_SUBDEPT:
PK_ID DEPT_ID SUB_DEPT_ID ----- ------- ----------- 1 1 3 2 1 4 3 1 5 4 3 6 5 3 7 6 6 9 7 2 8 8 2 10 9 2 1 9 rows selected.
下面显示的PLSQL通过部门(由DEPT_ID标识)和子系统或子部门(由SUB_DEPT_ID标识)进行工作,如原始问题陈述中所述:
“...取1 DEPT_ID然后程序应该执行3,4,5,然后首先它应该执行3如果3的孩子存在(这里他们是6,7,再次它将执行6的孩子9和所以,如果4岁的孩子存在(这里不存在)那么4,那么对于5岁的孩子(这里不存在)等等......“
set serveroutput on; begin for i in ( select dept_id, sub_dept_id,level from dept_subdept START WITH dept_id = &START_WITH_DEPT_ID connect by prior sub_dept_id=dept_id order by level, sub_dept_id ) loop dbms_output.put_line('exec someProcedure('||i.dept_id||','||i.sub_dept_id||');'); end loop; end; /
Enter value for start_with_dept_id: 1
exec someProcedure(1,3); exec someProcedure(1,4); exec someProcedure(1,5); exec someProcedure(3,6); exec someProcedure(3,7); exec someProcedure(6,9); PL/SQL procedure successfully completed.
这里使用START_WITH_DEPT_ID = 3再次运行PLSQL:
SQL> / Enter value for start_with_dept_id: 3 exec someProcedure(3,6); exec someProcedure(3,7); exec someProcedure(6,9); PL/SQL procedure successfully completed.
......再一次使用START_WITH_DEPT_ID = 4 (没有孩子,无事可做):
SQL> / Enter value for start_with_dept_id: 4 PL/SQL procedure successfully completed.