1、寫mysql存儲過程應注意的幾點:mysql
一、聲明變量(declare)時要注意字符集,用變量存儲表字段時,表字段與變量的字符編碼要一致。sql
二、mysql的字符合並不能用‘+’號,必須用concat函數。函數
三、每一個遊標必須使用不一樣的declare continue handler for not found set done=1來控制遊標的結束。oop
實例:編碼
delimiter // -- 將語句結束標誌設爲雙斜槓,默認以逗號做爲語句結束標誌 CREATE PROCEDURE `proxy_infreeze`() BEGIN DECLARE done INT DEFAULT 0; DECLARE proxy_infreeze_amount DECIMAL(10,2) ; -- 注意位長也要聲明,會有進位或捨棄 DECLARE customerId BIGINT ; DECLARE cursor_avgScore CURSOR FOR ( SELECT SUM(update_amount) proxy_infreeze_amount,b.customer_id FROM customer_bill b WHERE bill_type =4 AND statu = 1 AND create_at > DATE_ADD(NOW(), INTERVAL -9 DAY) AND create_at < DATE_ADD(NOW(), INTERVAL -7 DAY) GROUP BY b.customer_id ); DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- 控制遊標的結束。 OPEN cursor_avgScore; FETCH cursor_avgScore INTO proxy_infreeze_amount,customerId; out_loop: LOOP UPDATE customer_account SET proxy_freeze_amount =proxy_freeze_amount-proxy_infreeze_amount WHERE customer_id = customerId; FETCH cursor_avgScore INTO proxy_infreeze_amount,customerId; IF done =1 THEN LEAVE out_loop; END IF; END LOOP out_loop; CLOSE cursor_avgScore; update customer_bill set statu = 2 WHERE bill_type =4 AND statu = 1 AND create_at > DATE_ADD(NOW(), INTERVAL -9 DAY) AND create_at < DATE_ADD(NOW(), INTERVAL -7 DAY); END // delimiter ;
二 、 定時器code
--查看定時策略是否開啓 show variables like '%event_sche%'; -- 開啓定時策略 set global event_scheduler=1; -- 建立定時任務event(事件) create event batchDel_overdue_order_event on schedule every 1 day starts '2016-10-01 23:50:00' on completion preserve disable do call batchDel_overdue_order(); --查看定時任務event(事件),能夠查看本機全部的事件 SELECT event_name,event_definition,interval_value,interval_field,status FROM information_schema.EVENTS; alter event batchDel_overdue_order_event on completion preserve enable;--開啓定時任務 alter event second_event on completion preserve disable;--關閉定時任務