2016-01-18 41 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