mysql存储过程,结果集遍历,if -else

BEGIN
#Routine body goes here...
#根据指定用户,统计用户关注,粉丝,黑名单个数
#用户关注或取消关注,拉黑或取消拉黑时调用该存储过程




  DECLARE followCount BIGINT DEFAULT 0 ;
DECLARE fansCount BIGINT DEFAULT 0 ;
DECLARE blackCount BIGINT DEFAULT 0 ;


 #创建接收游标数据的变量  
    declare c BIGINT;  
    declare n BIGINT(20);  
    #创建总数变量  
    declare total int default 0;  
    #创建结束标志变量  
    declare done int default false;  
    #创建游标  
    declare follow_cur cursor for select userid,count(*) count from attention GROUP BY userid;  
    declare fans_cur cursor for select attention_userid,count(*) count from attention GROUP BY attention_userid;  
    declare black_cur cursor for select userid,count(*) count from black GROUP BY userid;  
    #指定游标循环结束时的返回值  
    declare continue HANDLER for not found set done = true;  




  

#传用户id时,统计该用户即可
IF uid != 0 THEN

  SELECT  COUNT(*)  INTO  followCount   FROM  attention    where      userid=uid ; 
  SELECT  COUNT(*)  INTO  fansCount     FROM  attention     where    attention_userid=uid ; 
  SELECT  COUNT(*)  INTO  blackCount    FROM  black         where    userid=uid ; 


UPDATE u_user set attention=followCount,fans=fansCount,black_count=blackCount where id=uid;
ELSE
   #不传用户id时,统计全部用户
   
   
    #设置初始值  
    set total = 0;  
    #打开游标  
    open follow_cur;  
    #开始循环游标里的数据  
    read_loop:loop  
    #根据游标当前指向的一条数据  
    fetch follow_cur into c,n;  
    #判断游标的循环是否结束  
    if done then  
        leave read_loop;     #跳出游标循环  
    end if;  
    #获取一条数据时,将count值进行累加操作,这里可以做任意你想做的操作, 


update u_user set attention=n where id=c;
  #输出结果  


    #结束游标循环  
    end loop;  
    #关闭游标  
    close follow_cur;  


 SET done = FALSE;-- 两个游标的情况下,注意在遍历第二个游标之前将done标志设为FALSE


 open fans_cur;  
    #开始循环游标里的数据  
    read_loop:loop  
    #根据游标当前指向的一条数据  
    fetch fans_cur into c,n;  
    #判断游标的循环是否结束  
    if done then  
        leave read_loop;     #跳出游标循环  
    end if;  
    #获取一条数据时,将count值进行累加操作,这里可以做任意你想做的操作, 


update u_user set fans=n where id=c;
  #输出结果  


    #结束游标循环  
    end loop;  
    #关闭游标  
    close fans_cur;  
 


SET done = FALSE;-- 两个游标的情况下,注意在遍历第二个游标之前将done标志设为FALSE
 open black_cur;  
    #开始循环游标里的数据  
    read_loop:loop  
    #根据游标当前指向的一条数据  
    fetch black_cur into c,n;  
    #判断游标的循环是否结束  
    if done then  
        leave read_loop;     #跳出游标循环  
    end if;  
    #获取一条数据时,将count值进行累加操作,这里可以做任意你想做的操作, 


update u_user set black_count=n where id=c;
  #输出结果  


    #结束游标循环  
    end loop;  
    #关闭游标  
    close black_cur;  
  


    
  




 END IF;


END

猜你喜欢

转载自blog.csdn.net/u014755645/article/details/72918446