2016-01-18 22 views
0

如何在下面的分类帐表中使用循环来更新使用存储过程的余额。带有循环和更新的SQL存储过程

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 
+0

SELECT PersonID,dr,cr,sum(bal)FROM Ledger GROUP by PersonID; –

回答

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