我在这里遇到了问题。我有两个表pp_gabungan
和jharga
。 Jharga
用于存储预算值,另一方面pp_gabungan
用于保存图书采购数据。
我需要使用游标自动更新eks
表上的pp_gabungan
字段。
例如,只要sum of (eks*harga)
中包含的价格总和小于budget
,eks字段的值就应该增加1。但问题是这段代码有效,但它只更新了一次。
只要sum(eks*harga)
小于budget
,它就不应该停止递增。你能帮助我,我是否应该添加更多循环?如果是的话......应该怎么做?
这是我的代码:
DECLARE
bb jharga.budget%type;
tharga jharga.budget%type;
CURSOR eksupdate IS
SELECT
isbn,judul,frekuensi,stok,harga,prioritas,eks,kelompok,bobot
FROM pp_gabungan
FOR UPDATE OF eks NOWAIT;
autoeks eksupdate%ROWTYPE;
BEGIN
OPEN eksupdate; -- rows are locked.
select budget into bb from jharga;
select sum(eks*harga) into tharga from pp_gabungan;
LOOP
FETCH eksupdate INTO autoeks;
--EXIT WHEN eksupdate%NOTFOUND;
tharga:=(autoeks.eks*autoeks.harga);
IF tharga <= bb THEN
UPDATE pp_gabungan
SET eks = autoeks.eks+1
WHERE CURRENT OF eksupdate ;
END IF;
exit when tharga > bb;
END LOOP;
--COMMIT; -- rows are unlocked.
CLOSE eksupdate;
end;
答案 0 :(得分:0)
如果我理解您的要求,您希望所有行的eks
列增加1,只要所有行的eks*harga
总和在预算范围内。第一次通过后,如果仍有预算,您想再次重复此过程。
我已修改了使用FOR
循环打开游标,因为我对这种语法感到满意。
DECLARE
bbs jharga.budget%TYPE;
tharga jharga.budget%TYPE;
balance NUMBER;
CURSOR eksupdate
IS
SELECT isbn, judul, frekuensi, stok, harga, prioritas, eks,
kelompok, bobot
FROM pp_gabungan
FOR UPDATE OF eks NOWAIT;
BEGIN
--get the allotted budget
SELECT budget
INTO bbs
FROM jharga;
--get the total amount
SELECT SUM (eks * harga)
INTO tharga
FROM pp_gabungan;
balance := bbs - tharga; -- the balance amount
--as long as the balance is more than zero , the cusor will be repeatedly called.
-- also note that i've given a name to the loop, loop1
<<loop1>>
WHILE balance > 0
LOOP
--for loop to open/fetch the cursor, this has been given name loop2
<<loop2>>
FOR i IN eksupdate
LOOP
--if the balance amount is less than that of harga, exit from both the loops
EXIT loop1 WHEN balance < i.harga;
--if balance amount is more than harga, update the eks by 1
UPDATE pp_gabungan
SET eks = autoeks.eks + 1
WHERE CURRENT OF eksupdate;
--decrease the balance by harga
balance := balance - i.harga;
END LOOP loop2;
END LOOP loop1;
COMMIT;
EXCEPTION
WHEN OTHERS
THEN
ROLLBACK;
DBMS_OUTPUT.put_line (SQLERRM);
END;