本篇文章主要讲解,我的一个案例,使用存储过程和游标循环数据列表,并且做一些操作,比如保存一些数据,修改一些数据;
MySQL使用存储过程循环数据列表?
while循环
CREATE PROCEDURE proc_while ()
BEGIN
DECLARE num INT ;
SET num = 0 ;
WHILE num < 10 DO
SELECT
num ;
SET num = num + 1 ;
END WHILE ;
END
repeat循环
CREATE PROCEDURE proc_repeat ()
BEGIN
DECLARE i INT ;
SET i = 0 ;
repeat
select i;
set i = i + 1;
until i >= 5
end repeat;
END
loop循环
BEGIN
declare i int default 0;
loop_label: loop
set i=i+1;
if i<8 then
iterate loop_label;
end if;
if i>=10 then
leave loop_label;
end if;
select i;
end loop loop_label;
END
3.1、先删除已经存在的临时表和存储过程
drop table TempNoIntroAgent;
drop table TempNoBelongAgent;
drop table TempSameAgent;
drop PROCEDURE pro_sel_agent
3.2、新建临时表(注意:我这里的临时表就是真实的表,只是临时用一下,然后删掉的)
create TABLE TempNoIntroAgent(
AgentId BIGINT NOT NULL,
LoginId VARCHAR(50) not NULL
);
create TABLE TempNoBelongAgent(
AgentId BIGINT NOT NULL,
LoginId VARCHAR(50) not NULL
);
create TABLE TempSameAgent(
AgentId BIGINT NOT NULL,
LoginId VARCHAR(50) not NULL
);
3.3、新建存储过程,其中使用游标保存数据列表,然后循环
CREATE PROCEDURE pro_sel_agent()
BEGIN
DECLARE done INT DEFAULT 0 ;
DECLARE _agentid int;
DECLARE _loginid VARCHAR(50);
DECLARE agentnum int;
#新建游标
declare cur1 CURSOR FOR select Id,LoginId from Agent;
set agentnum = (select count(*) from Agent where BonusStatus = 0);
#打开游标
OPEN cur1;
FETCH cur1 into _agentid,_loginid; //使用fetch into 语法把游标的每一行的数据赋值给临时变量
WHILE agentnum >0 DO
set @agentId=(select Id from Agent where LoginId =_loginid);
set @noIntroNum = (select count(*) from AgentIntroductionBiz where IntroducerId = @agentId);
set @noBelongNum = (select count(*) from AgentBelongBizPosition where ParentId = @agentId);
if @noIntroNum > 0 and @noBelongNum = 0 THEN
INSERT into TempNoIntroAgent(AgentId,LoginId)
values(_agentid,_loginid);
ELSEIF @noBelongNum > 0 and @noIntroNum = 0 THEN
INSERT into TempNoBelongAgent(AgentId,LoginId)
values(_agentid,_loginid);
ELSE
set @sameNum = (
select count(b.LoginId) FROM(
select a.LoginId
from AgentIntroductionBiz as ai
INNER JOIN Agent as a on a.Id=ai.Id
where ai.IntroducerId=@agentId
)as a
INNER JOIN(
SELECT a.LoginId
from AgentBelongBizPosition as ap
INNER JOIN Agent as a on a.Id=ap.Id
where ap.ParentId=@agentId
) as b on b.LoginId=a.LoginId
);
IF @sameNum > 0 THEN
INSERT into TempSameAgent(AgentId,LoginId)
values(_agentid,_loginid);
end if;
end IF;
set agentnum = agentnum-1;
FETCH cur1 into _agentid,_loginid; //注意:这里也要使用fetch into 语法把游标的每一行的数据赋值给临时变量,否则临时变量的值就一直不会改变;
END WHILE;
CLOSE cur1;
END;
好了先写到这了,有问题的话,可以一起交流下;
业余时间赚点零花钱点这里