Oracle中针对层次数据所设计的专用SQL查询语句

假设有组织数据表orgstdstruct,其中包含UNITID,PUNITID,UNITNAME等字段,其中PUNITID是本表UNITID字段的外键,那么在ORACLE中可以通过以下语句直接查询出具有层次关系的数据,使用起来非常方便。

 

select level,unitid,punitid,unitname from orgstdstruct
start with punitid is null
connect by prior unitid = punitid

 

语法结构如下:

SELECT [LEVEL],column,expr...

FROM table

[WHERE condition(s)]

[START WITH condition(s)]

[CONNECT BY PRIOR condition(s)];

其中LEVEL字段是可选的,表示查询出来的数据层级

 

在Oracle 10g中,增加了一个新函数,叫做CONNECT_BY_ISLEAF,如果行的值为0表示非叶子节点,1表示叶子节点,示例如下:

 

select level,unitid,punitid,unitname,

(case when connect_by_isleaf=1 then '叶子' else '不是叶子' end) isleaf

from orgstdstruct
start with punitid is null
connect by prior unitid = punitid

 

另外,Oracle 10g还提供了CONNECT_BY_ISCYCLE和NOCYCLE关键字来解决循环问题,示例如下:

 

select level,connect_by_iscycle,unitid,punitid,unitname from orgstdstruct
start with punitid is null
connect by nocycly prior unitid = punitid


这样可以避免循环参加查询操作,并且通过CONNECT_BY_ISCYCLY得到哪个节点发生循环,0表示未循环,1表示循环

 

遗憾的是这种语法目前SQLServer还未支持,也不是标准的T-SQL语法。

posted @ 2009-01-22 15:08  mp3 swf  阅读(578)  评论(0编辑  收藏  举报