我在存储过程中创建了包含 52600 条记录的临时表,我想迭代临时表并为每一行更新一列。
这里我有两个游标
,一个用于临时表,第二个用于其他表,比如具有三行的 table2,我必须从临时表中取出 1 行并遍历 table2 并比较,如果找到匹配项我正在更新临时表中的列。
此过程需要花费大量时间,大约 500 秒,在 存储过程
中使用游标和循环执行此操作好还是在代码中执行此操作好?
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
最佳答案
如果我对你的光标的理解是正确的,你将遍历临时表中的所有记录并查看 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 .如果我误解了,请告诉我。
祝你好运。
关于mysql - 存储过程中的嵌套游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14846666/