手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

MySQL存储过程递归调用

[日期:2012-06-14] 来源:Linux社区  作者:geloin/ [字体:大 中 小]
3. 根据分类代号取得子分类的个数。
  1. CREATE FUNCTION category_findChildrenCountByCode(cCode varchar(200)) RETURNS int(11)  
  2. BEGIN  
  3. -- 调用的函数或存储过程:无  
  4. -- 被调用于函数或存储过程:category_findCodesByParentCode_queryAndInsert  
  5.     declare finished int default 0;  
  6.     declare count int;  
  7.     declare cur cursor for select count(id) from tb_system_category where c_code like CONCAT(cCode,'%') and c_code != cCode;  
  8.     declare continue handler for not found set finished = 1;  
  9.     open cur;  
  10.     fetch cur into count;  
  11.     close cur;  
  12.     if count is null then  
  13.         return 0;  
  14.     else  
  15.         return count;  
  16.     end if;  
  17. END  
        4. 从临时表中查出结果并组合成字符串。
  1. CREATE FUNCTION category_generateResult(cRand varchar(50)) RETURNS varchar(4000) CHARSET utf8  
  2. BEGIN  
  3. -- 调用的函数或存储过程:无  
  4. -- 被调用于函数或存储过程:category_findCodesByParentCode  
  5.     declare finished int default 0;  
  6.     declare result varchar(20000) default '';  
  7.     declare thisResult varchar(200) default '';  
  8.     declare cur cursor for select c_result from tb_system_temp_category_categoryTree where c_rand = cRand;  
  9.     declare continue handler for not found set finished = 1;  
  10.     open cur;  
  11.     fetch cur into thisResult;  
  12.     while finished = 0 do  
  13.           
  14.         set result = concat(result, thisResult, ',');  
  15.       
  16.         fetch cur into thisResult;  
  17.     end while;  
  18.     close cur;  
  19.   
  20.     if result is null then  
  21.         return result;  
  22.     else  
  23.         if RIGHT(result,1) = ',' then  
  24.             set result = SUBSTR(result, 1, CHAR_LENGTH(result) - 1);  
  25.         end if;  
  26.         return result;  
  27.     end if;  
  28. END  
        在MySQL中,不能够直接使用函数实现递归,在上例中,使用存储过程递归调用,将需要的值存储到临时表中,然后通过对临时表进行操作后取得结果。linux
相关资讯       MySQL存储过程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款