begin -- 需要定义接收游标数据的变量 DECLARE matter_Year VARCHAR(50); DECLARE matter_Count INT; DECLARE matter_Money DECIMAL(20,2); -- 批准经费总额 DECLARE research_Money DECIMAL(20,2); DECLARE b VARCHAR(5000); DECLARE no_more_record INT DEFAULT 0; DECLARE cur_record CURSOR FOR SELECT f_matter_year,count(*),sum(IFNULL(f_matter_app_funding, 0)) from t_matter GROUP BY f_matter_year; /*首先这里对游标进行定义*/ DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_record = 1; /*这个是个条件处理,针对NOT FOUND的条件,当没有记录时赋值为1*/ OPEN cur_record; /*接着使用OPEN打开游标*/ FETCH cur_record INTO matter_Year, matter_Count,matter_Money; /*把第一行数据写入变量中,游标也随之指向了记录的第一行*/ WHILE no_more_record != 1 DO -- 批准经费总额 SELECT IFNULL(sum(t.f_matter_app_funding),0) into research_Money from t_research_program t where t.f_matter_year=matter_Year GROUP BY t.f_matter_year; -- GROUP BY a.f_matter_year; SELECT research_Money; INSERT INTO t_test(yearNum,matterCount,matterMoney,researchMoney) VALUES(matter_Year,matter_Count,matter_Money,research_Money); FETCH cur_record INTO matter_Year, matter_Count,matter_Money; END WHILE; CLOSE cur_record; /*用完后记得用CLOSE把资源释放掉*/ end
在游标循环的时候,获取research_Money 总是NULL。假如本人把matter_Year 设置成一个固定值得时候(set matter_Year =”2015″),获取的research_Money 就不是NULL了,这是为什么?
40
— 需要定义接收游标数据的变量
DECLARE matter_Year VARCHAR(50);
DECLARE matter_Count INT;
DECLARE matter_Money DECIMAL(20,2);
— 批准经费总额
DECLARE research_Money DECIMAL(20,2);
DECLARE b VARCHAR(5000);
DECLARE no_more_record INT DEFAULT 0;
DECLARE cur_record CURSOR FOR SELECT f_matter_year,count(*),sum(IFNULL(f_matter_app_funding, 0)) from t_matter GROUP BY f_matter_year; /*首先这里对游标进行定义*/
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_record = 1; /*这个是个条件处理,针对NOT FOUND的条件,当没有记录时赋值为1*/
OPEN cur_record; /*接着使用OPEN打开游标*/
FETCH cur_record INTO matter_Year, matter_Count,matter_Money; /*把第一行数据写入变量中,游标也随之指向了记录的第一行*/
WHILE no_more_record != 1 DO
— 批准经费总额
SELECT IFNULL(sum(t.f_matter_app_funding),0) into research_Money from t_research_program t where t.f_matter_year=matter_Year GROUP BY t.f_matter_year;
— GROUP BY a.f_matter_year;
SELECT research_Money;
INSERT INTO t_test(yearNum,matterCount,matterMoney,researchMoney) VALUES(matter_Year,matter_Count,matter_Money,research_Money);
set no_more_record = 0;
FETCH cur_record INTO matter_Year, matter_Count,matter_Money;
END WHILE;
CLOSE cur_record; /*用完后记得用CLOSE把资源释放掉*/
end