通过此SQL语句
select * from tree
查看原始数据如下:
我们要想得到如下的一个树形查询结果如下图所示(包含 ROOT, LEVEL, IS_LEAF, PATH 四个字段):
可执行如下SQL语句:
select connect_by_root(child_col) root, level , decode(connect_by_isleaf,0,'No',1,'Yes') is_leaf, sys_connect_by_path(child_col,'/') path
from tree
start with parent_col is null connect by prior child_col=parent_col;
树形查询的重点在于 start with ... connect by prior .... 语句
以及 connect_by_root ,connect_by_isleaf,sys_connect_by_path这三个函数, decode是一般常用的函数。
其他参考:http://www.cnblogs.com/tongzhenhua/archive/2008/09/23/1297253.html
动态查询语句例子:
declare
n_rows number;
v_sql_stmt varchar2(50);
v_table_name varchar2(20);
v_name varchar2(20);
begin
v_table_name := 'tree';
v_sql_stmt := 'select count(*) from ' || v_table_name || ' where parent_col = :1';
v_name := 'asia';
dbms_output.put_line(v_sql_stmt);
execute immediate v_sql_stmt into n_rows using v_name;
dbms_output.put_line('The number of rows of' || v_table_name || 'is ' || n_rows);
end;