3

Hi I wrote a while loop in Oracle SQL. I think the syntax is good, but it cannot be excute for some reason. Can someone help me to check where the problems is? Many thanks!

It only uses one table "test_fruit", with colume "price".

BEGIN
  WHILE (select sum(price) from test_fruit) <50 LOOP
    update test_fruit set price = price + 5; 
    EXIT WHEN (select max(price) from test_fruit) >20; 
  END LOOP;
END;

By the way, What I am trying to do is to update table, and increase the price of each row, until the sum is 50. Also max price in each row cannot exceed 20. thanks!

user2679074
  • 77
  • 1
  • 1
  • 6

1 Answers1

7

There are several ways to do it but you can try something like this :

DECLARE
  l_sumprice INTEGER := 0;
  l_maxprice INTEGER := 0;
BEGIN
  WHILE l_sumprice < 50 AND l_maxprice < 20 LOOP
    UPDATE test_fruit SET price = price + 5;
    SELECT sum(price), max(price) INTO l_sumprice, l_maxprice FROM test_fruit;
  END LOOP;
END;

Try the fiddle

Yann39
  • 14,285
  • 11
  • 56
  • 84