通過此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,'/') pathfrom treestart 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;