0

我这里有问题。我有两张桌子pp_gabunganjharga. Jharga用于存储预算值,另一方面pp_gabungan用于保存书籍采购数据。我需要使用光标自动更新表eks上的字段。pp_gabungan例如,只要包含 from 的总价格sum of (eks*harga)小于budget,则 eks 字段的值应加一。但问题是这段代码有效,但它只更新一次。只要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;
4

1 回答 1

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;
于 2013-06-03T06:36:42.257 回答