mysql存储过程

DELIMITER $$

DROP PROCEDURE IF EXISTS `lekan`.`UpdateVideoStats` $$
CREATE DEFINER=`root`@`%` PROCEDURE `UpdateVideoStats`()
begin
     declare done int DEFAULT 0;
    declare vId bigint ;
    declare tNum int;
    declare cur1 cursor for
    select videoId from video where parentId=0 and status=2 ;
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

    open cur1;
    repeat
        fetch cur1 into vId;
        select count(v.videoId) into tNum from video_stats v where v.videoId=vId;
        if tNum=0 then
                insert into video_stats(videoId,hits,collect,score,comment,scoreNum,recommend ) values(vId,0,0,0,0,0,0 );
        end if;
        update video_stats v set v.score =(select IFNULL((select ROUND(avg(vs.userScore),1) from user_video_score vs where  vs.videoId=vId),0)) where v.videoId=vId;
        update video_stats v set v.hits = (select count(uv.videoId )  from USER_WATCHED_VIDEO uv where  uv.videoId=vId ) where v.videoId=vId;
        update video_stats v set v.collect= ( select  count(uv.videoId) from USER_COLLECTED_VIDEO  uv where uv.videoId=vId) where v.videoId=vId;
        update video_stats v set v.scoreNum = (select count(vs.videoId) from user_video_score vs where  vs.videoId=vId) where v.videoId=vId;
        update video_stats v set v.comment=(select count(vc.commentId) from VIDEO_COMMENT vc where vc.videoId=vId) where v.videoId=vId;
    until done end repeat;
    close cur1;
end $$

DELIMITER ;

你可能感兴趣的:(mysql)