mysql游標巢狀迴圈例子

2021-08-15 06:20:46 字數 2392 閱讀 2289

create procedure finance_recivedetail(customer_id varchar(20))

begin

declare done int default 0;

declare id_a bigint;

declare pre_recv_remain_a decimal(12,2);

declare storageid_a varchar(20);

declare pre_recv_remain_b decimal(12,2);

declare storageid_b varchar(20);

declare cur1 cursor for select id,pre_recv_remain,storage_id

from `t_fin_pre_recive` where

pre_recv_customer_id = customer_id

and pre_recv_remain>0 order by create_time asc;

declare cur2 cursor for select abs(pre_recv_remain),storage_id from

`t_fin_pre_recive` where pre_recv_remain<0 and pre_recv_customer_id=customer_id;

declare continue handler for not found set done = 1;

-- open cur1;

open cur2;

while done = 0 do -- 要有不然迴圈一次

fetch cur2 into pre_recv_remain_b,storageid_b; -- 退款的

if not done then -- 要有不然迴圈一次

open cur1;

while done = 0 do -- 要有不然迴圈一次

fetch cur1 into id_a, pre_recv_remain_a,storageid_a;

if not done then -- 要有不然迴圈一次

if (pre_recv_remain_a < pre_recv_remain_b and storageid_b=storageid_a) then

insert into `t_fin_pre_recive_order` (

pre_recv_id,

order_id,

order_amount,

order_type,

create_time

) values (id_a,'',pre_recv_remain_a,2,now());

update `t_fin_pre_recive` set pre_recv_remain ='0' where id=id_a;

elseif pre_recv_remain_a = pre_recv_remain_b and storageid_b=storageid_a then

insert into `t_fin_pre_recive_order`(

pre_recv_id,

order_id,

order_amount,

order_type,

create_time

) values (id_a,'',pre_recv_remain_a,2,now());

update `t_fin_pre_recive` set pre_recv_remain ='0' where id=id_a;

elseif pre_recv_remain_a > pre_recv_remain_b and storageid_b=storageid_a then

insert into `t_fin_pre_recive_order` (

pre_recv_id,

order_id,

order_amount,

order_type,

create_time

) values (id_a,'',pre_recv_remain_b,2,now());

update `t_fin_pre_recive` set pre_recv_remain =(pre_recv_remain_a-pre_recv_remain_b) where id= id_a;

end if;

end if;

end while ;

close cur1;

set done = 0 ; -- 重點設定為0 繼續迴圈不然done=1時直接不迴圈了,外層的也不迴圈了

end if;

end while;

close cur2;

end

儲存過程 游標巢狀迴圈

alterprocedure dbo asdeclare startnum nvarchar 255 declare endnum nvarchar 255 declare insurancetype nvarchar 255 declare company id nvarchar 255 decl...

mysql 游標巢狀使用

解決方案 從a表取乙個欄位的值和從b表取乙個欄位的值一一組合作為插入資料來源。drop procedure if exists test team user create procedure test team user begin declare done int default 0 declar...

sql 游標的使用 游標FOR迴圈小例子

例子 顯示emp表所有雇員名及其工資 複製 如下 declare cursor emp cursor is select ename,sal from emp begin for emp record in emp cursor loop dbms output.put line 姓名 emp re...