MySQL使用递归存储过程实现树状结构,实现Oracle的Connect By 功能



1 创建一个数据表 
  1. CREATE TABLE `tree` (  
  2.   `id` int(10) NOT NULL,  
  3.   `fid` int(10) NOT NULL  
  4. );  

id 是编号 
fid 是上级编号, 顶层是0或者你自己定义 

2 创建临时表 
create temporary table if not exists  tmp_table(id bigint(20),fid bigint(20),lvl int)// 

3 编写存储过程 
  1. DELIMITER //  
  2. drop procedure if exists  useCursor //  
  3. -- 建立存储过程   
  4. -- JAVA世纪网 <a target="_blank" href="www.java2000.net">www.java2000.net</a> 老紫竹  
  5. CREATE PROCEDURE useCursor(iid bigint(20),lvl int)  
  6.     BEGIN                   
  7.          -- 局部变量定义  
  8.          declare tid bigint(20) default -1 ;  
  9.          declare tfid bigint(20) default -1 ;  
  10.            
  11.          -- 游标定义  
  12.          declare cur1 CURSOR FOR select id,fid from tree where fid=iid ;  
  13.            
  14.          -- 游标介绍定义  
  15.          declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tid = null,tfid=null;  
  16.   
  17.                  SET @@max_sp_recursion_depth = 10;  
  18.                             
  19.          -- 开游标  
  20.          OPEN cur1;  
  21.          FETCH cur1 INTO tid,tfid;  
  22.   
  23.          WHILE ( tid is not null )   
  24.          DO  
  25.           insert into tmp_table values(tid,tfid,lvl);  
  26.           -- 树形结构数据递归收集到建立的临时表中  
  27.           call useCursor(tid,lvl+1);  
  28.           FETCH cur1 INTO tid,tfid ;  
  29.        END WHILE;  
  30.     END;//  
  31. DELIMITER ;  



4 调用方式,并删除临时表 

call useCursor(2,0); 
select * from tmp_table ; 

5 删除临时表 
drop temporary table if  exists  tmp_table ; 


6 运行效果 
数据内容 


运行结果 

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值