我在存储过程中创建了52600条记录的临时表,我想迭代临时表并更新每一行的列。
这里我有两个cursors
一个用于临时表,第二个用于其他表说table2有三行,我必须从临时表中取1行并迭代通过table2并进行比较,如果匹配发现iam更新a临时表中的列。
这个过程耗费大约500秒的时间,使用游标和循环在stored procedure
中执行它是否合适?或者在代码中执行它是否合适?
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_repaymentDelay`()
BEGIN
drop table if exists loan_repayed_temp;
create temporary table loan_repayed_temp ( l_id int primary key, loan_Id int, installmentNo int,date_Diff int,interval_id int default 0);
insert into loan_repayed_temp (l_id,loan_Id,installmentNo,date_Diff)
select lrs.id ,lrs.loan_profile_id ,lrs.installment_number , datediff(curdate(), lrs.estimated_payment_date) from
loanTable lp inner join loanrepaymentschedule lrs on lp.id = lrs.loan_profile_id and lp.state = 'REPAYMENT_IN_PROGRESS'
left join repayments r on lrs.loan_profile_id = r.loan_profile_id and r.repayment_number = lrs.installment_number
where r.loan_profile_id is null and lrs.estimated_payment_date < NOW()
;
BEGIN
declare done int default false;
declare lid, loanId, installmentNo , dateDiff int;
declare cursor2 cursor for select id, interval_range_min, interval_range_max from delay_interval;
declare cursor1 cursor for select l_id,loan_Id, installmentNo,date_Diff from loan_repayed_temp;
declare continue handler for not found set done = true;
open cursor1;
cursor1_loop : loop
fetch cursor1 into lid, loanId, installmentNo, dateDiff;
IF done THEN
LEAVE cursor1_loop;
END IF;
-- delay interval comparision --
BEGIN
declare i , min ,max int;
declare done2 int default false;
declare continue handler for not found set done2 = true;
open cursor2;
cursor2_loop: loop
fetch cursor2 into i, min, max;
IF done2 THEN
LEAVE cursor2_loop;
end IF;
if dateDiff >= min and dateDiff <= max then
-- insert into datedemo values(dateDiff,loanId,i);
update loan_repayed_temp set interval_id = i where l_id = lid;
leave cursor2_loop;
end if;
end loop cursor2_loop;
close cursor2;
END;
-- --
end loop cursor1_loop;
close cursor1;
END;
drop table loan_repayed_temp;
END
答案 0 :(得分:0)
如果我正确理解你的光标,你循环遍历临时表中的所有记录,看看date_diff字段是否在delay_interval表的最小值和最大值之间。如果是这样,我认为这将以相同的方式工作,应该更快:
UPDATE loan_repayed_temp l
INNER JOIN delay_interval d
ON l.date_Diff >= d.interval_range_min
AND l.date_Diff <= interval_range_max
SET l.interval_id = d.id
以下是SQL Fiddle示例。如果我误解了,请告诉我。
祝你好运。