sqlserver和oracle的递归查询

时间:2022-01-10 03:08:53

1.sqlserver递归查询方式

CTE:

if OBJECT_ID('tb','N') is not null 
 drop table tb; 
  
create table tb(id varchar(3) , pid varchar(3) , name varchar(10)); 
insert into tb values('001' , null , '广东省'); 
insert into tb values('002' , '001' , '广州市');  
insert into tb values('003' , '001' , '深圳市') ; 
insert into tb values('004' , '002' , '天河区') ; 
insert into tb values('005' , '003' , '罗湖区'); 
insert into tb values('006' , '003' , '福田区') ; 
insert into tb values('007' , '003' , '宝安区') ; 
insert into tb values('008' , '007' , '西乡镇') ; 
insert into tb values('009' , '007' , '龙华镇'); 
insert into tb values('010' , '007' , '松岗镇');  
/*查询id为003的所有子节点*/
select * from tb; 
 
 with cte as 
 ( 
 select a.id,a.name,a.pid from tb a where id='003' 
 union all  
 select k.id,k.name,k.pid  from tb k inner join cte c on c.id = k.pid (c.pid=k.id则查询所有父节点)
 )select * from cte

2.Oracle递归查询方式

select distinct * from T_IISS_LOCATION
       START WITH PARENTID='594463261'
       CONNECT BY PRIOR PARENTID=GID (查询PARENTID='594463261'的所有父节点)
   select distinct * from T_IISS_LOCATION
       START WITH PARENTID='594463261'
       CONNECT BY PRIOR GID=PARENTID(查询PARENTID='594463261'的所有子节点)