MySQL存储过程使用游标循环数据列表
本篇文章主要講解,我的一個案例,使用存儲過程和游標循環數據列表,并且做一些操作,比如保存一些數據,修改一些數據;
1、需求?
MySQL使用存儲過程循環數據列表?
?
2、先描述下MySQL有哪些循環的語法
while循環
CREATE PROCEDURE proc_while () BEGINDECLARE num INT ;SET num = 0 ;WHILE num < 10 DOSELECTnum ;SET num = num + 1 ;END WHILE ;ENDrepeat循環
CREATE PROCEDURE proc_repeat () BEGINDECLARE i INT ;SET i = 0 ;repeatselect i;set i = i + 1;until i >= 5end repeat;ENDloop循環
BEGINdeclare i int default 0;loop_label: loopset i=i+1;if i<8 theniterate loop_label;end if;if i>=10 thenleave loop_label;end if;select i;end loop loop_label;END3、循環語法已經介紹,現在給出具體案例代碼了
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;
?
好了先寫到這了,有問題的話,可以一起交流下;
?
業余時間賺點零花錢點這里
?
總結
以上是生活随笔為你收集整理的MySQL存储过程使用游标循环数据列表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Protobuf之proto文件编写规则
- 下一篇: Redis分布式锁实现方式