BEGIN -- 定義變量 DECLARE s int DEFAULT 0; DECLARE isE tinyint(1) DEFAULT 0; DECLARE vehicleId char(32); -- 車輛id DECLARE num decimal(5,2); -- 加油數量 單位升 DECLARE oilWear decimal(5,2); -- 百千米油耗 DECLARE mileage decimal(8,2) DEFAULT(0); -- 區間內的千米數 DECLARE beginTime datetime; -- 上上次加油時間 DECLARE endTime datetime; -- 上次加油時間 DECLARE addNum int DEFAULT 0; -- 添加條數 -- 定義遊標,並將sql結果集賦值到遊標中 DECLARE report CURSOR FOR select r.create_time as begin_time,r2.create_time as end_time,r.num,r.vehicle_id from mjm_refuel_record as r JOIN( select vehicle_id,create_time FROM mjm_refuel_record where TO_DAYS(NOW( )) - to_days(create_time) =1 GROUP BY vehicle_id ORDER BY create_time DESC ) as r2 on r.vehicle_id = r2.vehicle_id and r.create_time < r2.create_time GROUP BY r.vehicle_id ORDER BY r.create_time desc; -- 聲明當遊標遍歷完後將標誌變量置成某個值 DECLARE CONTINUE HANDLER FOR NOT FOUND SET s=1; -- 打開遊標 open report; -- 將遊標中的值賦值給變量,注意:變量名不要和返回的列名同名,變量順序要和sql結果列的順序一致 fetch report into beginTime,endTime,num,vehicleId; -- 當s不等於1,也就是未遍歷完時,會一直循環 while s<>1 do -- 執行業務邏輯 SELECT IFNULL(sum(today_mileage/10),0) into mileage from mjm_gps_record_collect WHERE vehicle_id = vehicleId and update_time>= beginTime and update_time <=endTime; -- 是否存在記錄 SELECT count(1) into isE from mjm_oil_wear_collect WHERE vehicle_id = vehicleId AND day = DATE(NOW()); IF mileage>0 THEN set oilWear = num*(100/mileage); IF isE THEN UPDATE mjm_oil_wear_collect SET oil_num = oilWear,oil_num = num,mileage = mileage,begin_time=beginTime,end_time=endTime WHERE vehicle_id = vehicleId AND day = DATE(NOW()); ELSE INSERT into mjm_oil_wear_collect(id,vehicle_id,day,oil_wear,oil_num,mileage,begin_time,end_time) VALUES(replace(UUID(),'-',''),vehicleId, DATE(NOW()),oilWear,num,mileage,beginTime,endTime); END IF; set addNum = addNum+1; END IF; -- 將遊標中的值再賦值給變量,供下次循環使用 fetch report into beginTime,endTime,num,vehicleId; -- 當s等於1時代表遍歷以完成,退出循環 end while; -- 關閉遊標 close report; RETURN addNum; END
該事例爲統計百千米車輛油耗作的存儲過程,而後後臺作定時任務。根據加油的時間範圍獲取車輛的里程,再根據里程與油耗算出上次的百千米油耗。sql