带有循环和更新的SQL存储过程

时间:2016-01-18 17:39:56

标签: mysql stored-procedures stored-functions

如何在以下分类帐表中执行循环以使用存储过程更新余额。

CREATE TABLE Ledger
(
PersonID int,
dr float,
cr float,
bal float
); 

INSERT INTO Ledger(PersonID, dr, cr, bal)
VALUES 
('1001',105,0,0),
('1001',0,5.25,0),
('1002',0,150,0),
('1001',0,15,0),
('1002',73,0,0); 

SELECT PersonID, dr, cr, bal FROM Ledger;

如何循环和更新余额

bal += (dr - cr);

并最后列出具有最后余额的PersonID。如何使用MySQL循环和更新分类帐?

期望输出更新查询

PersonID       Dr      Cr          Bal
1001           105     0           105
1001           0       5.25        99.75
1001           0       15          84.75


PersonID       Dr      Cr          Bal
1002           0       150         -150
1002           73      0            -77

预期输出SELECT查询

    PersonID       Dr      Cr          Bal
    1001           0       15          84.75
    1002           73      0           -77

1 个答案:

答案 0 :(得分:0)

请看下面的代码。应该解决你的问题。

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `addbal`()
BEGIN
declare no_record int default 0;
declare pi int;
declare newbal float default 0;
declare mydr,mycr,mybal float default 0;
declare cicle int default 0;
declare cur_ledger CURSOR FOR 
select personid,dr,cr,bal FROM Ledger order by personid;
declare continue handler for not found


set no_record = 1;
open cur_ledger;
set @prevbal = 0;

chg_bal: LOOP
 FETCH cur_ledger INTO pi,mydr,mycr,mybal;
 IF no_record = 1 THEN 
 LEAVE chg_bal;
 END IF;

IF @previd != pi then
set @prevbal = 0;
end if;
set @newbal = (mydr-mycr) + @prevbal;

update Ledger set bal = @newbal  where cr = mycr and dr = mydr and personid = pi ; 

set @prevbal = @newbal;
set @previd = pi;

END LOOP chg_bal;

close  cur_ledger;


END