0

I'm trying to learn more about using Oracle, and I'm trying to understand loops and how to use them. I've got this :

loop
update table
set amount=(amount+3)
exit when amount>=20
end loop;

Currently amount is 12, so I'd expect it to add 3 to amount until it reaches 21, because then it will be greater than 20. But the error I get is "ORA-00933: SQL command not properly ended" I've also got loop and exit underlined in red.

Am I missing something simple, or am I misunderstanding how to use loops?

2
  • You are missing a semicolon on the update statement. However, there is no need at all to use pl/sql to do this Commented Mar 5, 2018 at 16:17
  • 'SQL command not properly ended' is referring to lines 3 and 4 line where you are missing semi-colons. Commented Mar 5, 2018 at 16:19

2 Answers 2

2

You should use a BEGIN..END block for writing PL/SQL. For simulating your update operation through loops, you may use RETURNING INTO clause with a variable.

Although this solution is for your understanding, in real time it is not an efficient way to run Update statement in loop like this. It would be better to run a single update statement setting the final value.

Note: This works for a single row update.

SET SERVEROUTPUT ON
DECLARE 
v_amount NUMBER;

BEGIN
 LOOP

    UPDATE yourtable 
     SET amount = amount + 3 -- WHERE clause
       RETURNING amount 
    INTO v_amount;

    DBMS_OUTPUT.PUT_LINE(v_amount);

    EXIT when v_amount >= 20;
 END LOOP;
END;
/

15
18
21
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works. You're right that a single update statement would be best, this is a good way for me to see how I would do a loop if I needed to.
1

I understand that the objective here is to learn LOOPs in Oracle, yet the example chosen is not ideal. You may want to check about ContextSwitching. Avoid issuing SQLs/DMLs inside loops as far as possible. Also never use PL/SQL to perform that which can be done using SQL unless it costs too much CPU.

update yourtable
set amount = amount + trunc((20 - amount)/3) * 3
where amount <= 20;

commit;

Instead, I would advise that a good place to start learning about LOOPs in Oracle in a structured way is using OracleDocumentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.