1 创建一个数据表
id 是编号
fid 是上级编号, 顶层是0或者你自己定义
2 创建临时表
create temporary table if not exists tmp_table(id bigint(20),fid bigint(20),lvl int)//
3 编写存储过程
4 调用方式,并删除临时表
call useCursor(2,0);
select * from tmp_table ;
5 删除临时表
drop temporary table if exists tmp_table ;
6 运行效果
数据内容

运行结果
- CREATE TABLE `tree` (
- `id` int(10) NOT NULL,
- `fid` int(10) NOT NULL
- );
id 是编号
fid 是上级编号, 顶层是0或者你自己定义
2 创建临时表
create temporary table if not exists tmp_table(id bigint(20),fid bigint(20),lvl int)//
3 编写存储过程
- DELIMITER //
- drop procedure if exists useCursor //
- -- 建立存储过程
- -- JAVA世纪网 <a target="_blank" href="www.java2000.net">www.java2000.net</a> 老紫竹
- CREATE PROCEDURE useCursor(iid bigint(20),lvl int)
- BEGIN
- -- 局部变量定义
- declare tid bigint(20) default -1 ;
- declare tfid bigint(20) default -1 ;
- -- 游标定义
- declare cur1 CURSOR FOR select id,fid from tree where fid=iid ;
- -- 游标介绍定义
- declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tid = null,tfid=null;
- SET @@max_sp_recursion_depth = 10;
- -- 开游标
- OPEN cur1;
- FETCH cur1 INTO tid,tfid;
- WHILE ( tid is not null )
- DO
- insert into tmp_table values(tid,tfid,lvl);
- -- 树形结构数据递归收集到建立的临时表中
- call useCursor(tid,lvl+1);
- FETCH cur1 INTO tid,tfid ;
- END WHILE;
- END;//
- DELIMITER ;
4 调用方式,并删除临时表
call useCursor(2,0);
select * from tmp_table ;
5 删除临时表
drop temporary table if exists tmp_table ;
6 运行效果
数据内容

运行结果
