mysql循环(嵌套) 过程(带返回值)
DECLARE _cur CURSOR FOR SELECT语句
–第一种循环:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET loop_done=1;
OPEN _cur;
REPEAT
FETCH filedmsglist INTO 变量;
IF NOT loop_done THEN
–处理语句
END IF;
UNTIL loop_done END REPEAT;
CLOSE _cur;
–第二种循环:
open _cur;
loop_cur:loop
fetch _cur into 变量;
if _done=1 then
leave loop_cur;
end if;
–处理语句
end loop;
close _cur;
一个完整的嵌套循环例子(带返回值):
CREATE DEFINER=`root`@`localhost` PROCEDURE
`process_tag_filedmsg`(OUT `str_result` VARCHAR(512))
BEGIN
DECLARE fid int;
DECLARE frommsg varchar(255);
DECLARE tomsg varchar(255);
DECLARE ccmsg varchar(255);
DECLARE addr varchar(255);
DECLARE userid int;
DECLARE contexttagid int;
DECLARE classtypeid int;
DECLARE hemail varchar(255);
DECLARE loop_done int default 0;
DECLARE str varchar(255) default "";
DECLARE filedmsglist CURSOR FOR
SELECT am.id,am.from_msg,am.to_msg,am.cc_msg
FROM filedmsg am WHERE (am.checktag IS NULL)
OR (am.checktag =0) ORDER BY am.msg_date ASC ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET loop_done=1;
OPEN filedmsglist;
REPEAT
FETCH filedmsglist INTO fid,frommsg, tomsg, ccmsg;
IF NOT loop_done THEN
BEGIN
DECLARE loop_done1 int default 0;
DECLARE contactmgmtlist CURSOR FOR
SELECT c.user_id,c.contexttag_id , c.classtype_id,b.h_email
FROM contactmgmt c, awm_addr_book b
WHERE c.addr_id = b.id_addr;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET loop_done1=1;
OPEN contactmgmtlist;
REPEAT
FETCH contactmgmtlist INTO userid,contexttagid,classtypeid,hemail;
IF NOT loop_done1 THEN
IF (FIND_IN_SET(hemail,CONCAT(frommsg,',',tomsg,',',ccmsg))) THEN
INSERT INTO msgcontexttag
(msg_id,contexttag_id,classtype_id,tagname,msgdesc,user_id)
(select fid,contexttagid,classtype_id,tagname,tagdesc,userid
from contexttag where id=contexttagid);
update filedmsg set checktag=1 where id=fid;
END IF;
--set str=CONCAT(str,hemail);
END IF;
UNTIL loop_done1 END REPEAT;
CLOSE contactmgmtlist;
END;
-- set str=CONCAT(str,frommsg);
END IF;
UNTIL loop_done END REPEAT;
CLOSE filedmsglist;
set str_result=str;
END
调用:call process_tag_filedmsg(@a);
select @a;
更多参考:
http://shansun123.iteye.com/blog/1026084
http://blog.csdn.net/a600423444/article/details/6424360