这几天在写一个存储过程,反复优化了几次,从最开始的7分钟左右,优化到最后的几秒,并且这个过程中我的导师帮我指点了很多问题,这些指点都是非常宝贵的,独乐乐不如众乐乐,一起来分享这次的优化过程吧。
这个存过程的需求是这样的,抓取某个时间段内的订单明细,然后计算并汇总到某表即可。
于是乎,我写出第一版的存储过程,代码如下:
/******************************************/ /* 合并当前版本时间段内MO的维修换料需求 */ /* p_begin 起始时间 */ /* p_user 创建人 */ /* p_version 版本编码 */ /* p_version 需求版本头表id */ /* Created by wufei in 2013-10-29 */ /******************************************/ procedure clc_Mat_Addition_Require(p_begin date, p_user varchar2, x_result out varchar2, x_msg out varchar2) is v_count int; --处理行数 v_num number; --维修换料数 v_version_code mms_mo_ori_version.version_code%type; --版本号 v_version_id mms_mo_ori_version.version_id%type; --需求单头号 v_raise exception; begin v_version_code:=to_char(p_begin,'yyyyMMdd'); v_version_id := fun_mms_get_guid(); --查询历史版本表,已执行过不允许执行 select count(*) into v_count from mms_mo_ori_version mmov where mmov.version_code = to_char(p_begin,'yyyyMMdd'); if v_count>0 then raise v_raise; end if; v_count:=0; --生成新版本头数据 insert into mms_mo_ori_version (version_id, version_code, start_time, end_time, creation_date, created_by, mat_type) values (v_version_id, v_version_code, p_begin, p_begin+1, sysdate, p_user, 1);--类别:维修换料 for line in ( select cwr.inventory_item_id,cwr.item_code,cwr.description,sum(cwr.quantity_open) as quantity_open from ifce.cux_wip_requirement_v cwr, ifce.cux_wip_entity_all_v cwal where cwr.WIP_ENTITY_ID = cwal.WIP_ENTITY_ID and cwal.START_DATE >= p_begin and cwal.START_DATE < p_begin+1 and cwr.quantity_open > 0 group by cwr.INVENTORY_ITEM_ID,cwr.item_code,cwr.description ) loop --获取维修换料数 select ifce.wip_logistics.fun_get_Iqcquit_sum(line.ITEM_CODE,trunc(p_begin)) into v_num from dual; if (v_num >0) then --当维修换料需求比例数大于0时插入 insert into mms_mo_mat_require (mat_requireid, mat_id, mat_code, mat_desc, require_time, require_qty, status, creation_date, created_by, version, mat_type, super_market_inv_code) select fun_mms_get_guid(), line.inventory_item_id, line.item_code, line.description, p_begin, line.quantity_open*v_num, '0', sysdate, p_user, v_version_code, 1, '42B' from dual; v_count:=v_count+1; end if; end loop; commit; x_result:='Y'; x_msg:=to_char(v_count); exception when v_raise then x_result:='N'; x_msg:='当前日期已执行过维修换料运算。'; when others then rollback; x_result:='N'; x_msg:='程序异常'; end clc_Mat_Addition_Require;