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语法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值