| 
       
	今天在写存储过程,给其他表插入数据时,发现,我游标取出来的数据明明只有一条,但是在循环过程中,却发现插入了两条数据。下面是代码 
	BEGIN 
	#Routine body goes here... 
	DECLARE event_content1 VARCHAR(255); 
	DECLARE event_id1 INT; 
	DECLARE event_name VARCHAR(255); 
	DECLARE start_time1 TIMESTAMP; 
	DECLARE end_time1 TIMESTAMP; 
	DECLARE  result_counts1 INT; 
	DECLARE High_result_time1 TIMESTAMP; 
	DECLARE high_result_counts1 INT; 
	DECLARE start_result_time1 TIMESTAMP; 
	DECLARE start_result_name1 text; 
	DECLARE reposts_counts1 INT; 
	DECLARE comments_counts1 INT; 
	DECLARE attitude_counts1 INT; 
	DECLARE done INT DEFAULT FALSE; 
	DECLARE  cur cursor for SELECT id,event_content,create_time,finish_time FROM t_public_concern_event WHERE `status` = 1  ; 
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 
	OPEN cur; 
	TRUNCATE TABLE event_preview; 
	read_loop:LOOP 
	if done THEN 
	            LEAVE read_loop; 
	            END IF; 
	# 游标 获取事件列表 
	FETCH cur INTO event_id1,event_content1,start_time1,end_time1; 
	# 获取事件相关结果数 
	select COUNT(1) INTO result_counts1 from t_public_opinion_realtime_weibo WHERE title= event_content1; 
	# 获取事件最多的某一天,以及总数 
	SELECT counts,create_time into high_result_counts1,High_result_time1  FROM (select COUNT(1) as counts,DATE_FORMAT(create_time,"%Y-%m-%d") as create_time FROM t_public_opinion_realtime_weibo WHERE title=event_content1 GROUP BY DATE_FORMAT(create_time,"%Y-%m-%d")) as a WHERE a.counts = (SELECT MAX(counts) from (select COUNT(1) as counts,DATE_FORMAT(create_time,"%Y-%m-%d") FROM t_public_opinion_realtime_weibo WHERE title=event_content1 GROUP BY DATE_FORMAT(create_time,"%Y-%m-%d")) as b); 
	# 获取事件源头 
	SELECT text,create_time into start_result_name1,start_result_time1 from t_public_opinion_realtime_weibo WHERE title = event_content1 ORDER BY create_time LIMIT 1; 
	# 总转发 总点赞,总评论 
	select SUM(reposts_count) ,SUM(comments_count) , SUM(attitudes_count) INTO reposts_counts1,comments_counts1,attitude_counts1  from t_public_opinion_realtime_weibo WHERE title = event_content1;    
	INSERT INTO event_preview (event_id,start_time,end_time,result_counts,High_result_time,high_result_counts,start_result_time,start_result_name,reposts_counts,comments_counts,attitude_counts)VALUES(event_id1,start_time1,end_time1,result_counts1,High_result_time1,high_result_counts1,start_result_time1,start_result_name1,reposts_counts1,comments_counts1,attitude_counts1); 
	END LOOP; 
	CLOSE cur; 
	END 
	结果造成了游标取出来是一条,但是插入却出现两条: 
![]() 
	检查后发现没有错, 后来修改,查找,发现是Fetch  游标的位置不对,造成的。 
	正确的写法是在判断游标为空 也就是 IF 之前 fetch 游标: 
	OPEN cur; 
	TRUNCATE TABLE event_preview; 
	read_loop:LOOP 
	    # 在if 之前fetch 游标 
	    FETCH cur INTO event_id1,event_content1,start_time1,end_time1; 
	if done THEN 
	            LEAVE read_loop; 
	            END IF; 
	# 其他操作 
	        。。。。。。。 
	这样下来就没错了。 
(责任编辑:IT)  | 
    

