MySQL实现统计数据并插入数据的存储过程
统计存储过程,这里是将统计的结果插入一个表中,后台可以有定时任务来调此存储过程。以下业务是统计仓库中商品流转情况,包括:日期、商品总数、入库数量、出库数量。
BEGIN DECLARE ES_COR_CODE VARCHAR(20); -- 需要定义接收游标数据的变量 DECLARE table_ VARCHAR(50); -- 遍历数据结束标志 DECLARE done INT DEFAULT FALSE; -- 游标 DECLARE cur CURSOR FOR SELECT TABLE_NAME FROM (SELECT TABLE_NAME from information_schema.tables WHERE TABLE_NAME LIKE '%wm_item_transfer_%' AND TABLE_SCHEMA='wmscloud_test' ) allTables; -- 将结束标志绑定到游标 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; -- 打开游标 OPEN cur; -- 开始循环 read_loop: LOOP -- 提取游标里的数据,这里只有一个,多个的话也一样; FETCH cur INTO table_; -- 声明结束的时候 IF done THEN LEAVE read_loop; END IF; SET ES_COR_CODE=substring(table_,18); SET @INSERT_ITEM_TRANSFER=CONCAT('INSERT INTO wm_item_transfer_',ES_COR_CODE,' (WMIT_DATE,WMIT_STOCK_NUM,WMIT_INTO_ITEM_NUM,WMIT_OUT_ITEM_NUM) SELECT (SELECT date_sub(curdate(),interval 1 day) ) WMIT_DATE , (SELECT IFNULL(SUM(WMST_NOW_NUMBER),0) FROM wm_stock_',ES_COR_CODE,') WMIT_STOCK_NUM, (SELECT IFNULL(SUM(WMST_NOW_NUMBER),0) FROM wm_stock_',ES_COR_CODE,' WHERE WMST_RECEIVE_DATE BETWEEN date_sub(curdate(),interval 1 day) AND NOW() ) WMIT_INTO_ITEM_NUM, (SELECT IFNULL(SUM(WMOO_OUT_NUMBER),0) FROM wm_out_order_',ES_COR_CODE,' where SURE_DATE BETWEEN date_sub(curdate(),interval 1 day) AND NOW() ) WMIT_OUT_ITEM_NUM'); PREPARE INSERT_ITEM_TRANSFER FROM @INSERT_ITEM_TRANSFER; EXECUTE INSERT_ITEM_TRANSFER; END LOOP; -- 关闭游标 CLOSE cur; END