-- 如果上步游标操作没有读取到记录,则done 会被设置为 TRUE,退出 名称为myloop的循环 IF done THEN LEAVE tableloop; END IF;
-- 记录当前记录的区域编码 SET buf_code = vcode;
-- 判断自己是否是叶子节点 SELECT count(*) into var_count from adm_sys_area_info where parent = vcode;
if var_count = 0 then update adm_sys_area_info set tree_leaf = 1 where code = vcode; else update adm_sys_area_info set tree_leaf = 0 where code = vcode; end if;
set var_count = 0;
-- 循环查找自己的父节点 treeloop : LOOP
-- 判断自己是否存在父节点,用count来判断 SELECT count( * ) INTO var_count FROM adm_sys_area_info WHERE CODE = vparent;
IF var_count = 0 THEN -- 没有上级节点了,则开始处理以前找到的父节点 IF buf_update THEN-- 更新缓存的数据 -- buf_update 为TRUE 则说明找到过父节点
-- 下面两个记录处理拼接的字符串末尾多的逗号的问题 IF ( length( buf_parents ) > 0 ) THEN
SET buf_parents = LEFT ( buf_parents, CHAR_LENGTH( buf_parents ) - 1 ); END IF; IF ( length( buf_names ) > 0 ) THEN
SET buf_names = LEFT ( buf_names, CHAR_LENGTH( buf_names ) - 1 ); END IF;
-- 更新当前节点的父信息 UPDATE adm_sys_area_info SET parents = buf_parents, tree_names = buf_names ,tree_level = buf_tree_level WHERE CODE = buf_code;
ELSE -- 当前记录是根节点 update adm_sys_area_info set tree_level = 1 where code = buf_code; END IF;
-- 清理变量 SET buf_parents = ''; SET buf_names = ''; SET vparent = ''; SET buf_code = ''; SET buf_update = FALSE; SET buf_tree_level = 1;
-- 结束当前记录的处理循环 LEAVE treeloop;
ELSE -- 查找到了父节点 SET buf_update = TRUE; -- 查询当前节点的父节点信息 SELECT CODE, parent, area_name INTO var_code, var_pcode, var_name FROM adm_sys_area_info WHERE CODE = vparent;
-- 连接字符串 SET buf_parents = CONCAT_WS( ',', var_code, buf_parents ); SET buf_names = CONCAT_WS( ',', var_name, buf_names ); -- 记录当前查找到记录的父节点code SET vparent = var_pcode; SET buf_tree_level = buf_tree_level + 1;