这篇文章是2014年8月8日在QQ空间记录的一篇工作心得,我把它给搬过来,也让更多人能够参考,学习,借鉴吧!
主要是使用mysql写一个存储过程吧。
修改前的存储过程:
BEGIN
DECLARE temp_id int(11);
DECLARE stopFlag int(11);
DECLARE cnt int(11);
DECLARE cnt1 int(11);
DECLARE idx int(11);
DECLARE noticereport_cursor CURSOR for select id from (select n1.id from supervisor_noticereport n1 where n1.project_id = project_id and n1.status = 0) a;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET stopFlag = 1;
select count(id) from (select n1.id from supervisor_noticereport n1 where n1.project_id = project_id and n1.status = 0 ) a into cnt;
set idx = 0;
open noticereport_cursor;
REPEAT
FETCH noticereport_cursor into temp_id;
if idx < cnt then
<span style="color:#ff0000;">SELECT r1.report_id,r1.user_id as last_user,d1.group_id as last_user_group,'supervisor_noticereport' as model,r1.time,1 as type,n1.name ,d1.name as username
from supervisor_noticehistory r1, ess_userinfo u1, ess_department d1,supervisor_noticereport n1
where r1.user_id = u1.id and d1.id = u1.department_id and r1.report_id = temp_id and d1.group_id!=user_group_id and n1.id = r1.report_id
ORDER BY r1.id DESC
limit 1;</span>
end if;
set idx = idx + 1;
until stopFlag = 1 end repeat;
close noticereport_cursor;
END
修改之后的存储过程:
BEGIN
DECLARE temp_id int(11);
DECLARE stopFlag int(11);
DECLARE cnt int(11);
DECLARE cnt1 int(11);
DECLARE idx int(11);
DECLARE noticereport_cursor CURSOR for select id from (select n1.id from supervisor_noticereport n1 where n1.project_id = project_id and n1.status = 0) a;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET stopFlag = 1;
select count(id) from (select n1.id from supervisor_noticereport n1 where n1.project_id = project_id and n1.status = 0 ) a into cnt;
set idx = 0;
open noticereport_cursor;
REPEAT
FETCH noticereport_cursor into temp_id;
if idx < cnt then
<span style="color:#ff0000;">SELECT * FROM (SELECT r1.report_id,r1.user_id as last_user,d1.group_id as last_user_group,'supervisor_noticereport' as model,r1.time,1 as type,n1.name ,d1.name as username
from supervisor_noticehistory r1, ess_userinfo u1, ess_department d1,supervisor_noticereport n1
where r1.user_id = u1.id and d1.id = u1.department_id and r1.report_id = temp_id and n1.id = r1.report_id
ORDER BY r1.id DESC
limit 1) a WHERE a.last_user_group!= user_group_id ;</span>
end if;
set idx = idx + 1;
until stopFlag = 1 end repeat;
close noticereport_cursor;
END
我只想说语句位置摆放很关键!
哦,还有一个问题要说明,MySQL的5.5版本在游标里面有个bug,在5.6里面就修正了!!!