In PL/SQL, the FOR LOOP is one of the most commonly used control structures for iteration. A key concept within this loop is the iterand (also known as the loop index or loop counter). Understanding how the iterand behaves is crucial to avoid runtime errors and write efficient code.
What is a FOR LOOP Iterand?
The iterand in a FOR LOOP is a variable that is:
- Implicitly declared by Oracle when the loop starts
- Local to the loop (not accessible outside the loop)
- Read-only inside the loop
This means:
- You can read its value
- You cannot modify its value
- It ceases to exist after the loop ends
Important Rule
You cannot assign a value to the FOR LOOP iterand inside the loop.
Attempting to do so results in a compilation error because Oracle protects the loop counter from being altered manually.
Example: Attempt to Modify Iterand (Incorrect Usage)
SET SERVEROUTPUT ON;
BEGIN
FOR i IN 1..3 LOOP
IF i < 3 THEN
DBMS_OUTPUT.PUT_LINE(TO_CHAR(i));
ELSE
i := 2; -- ❌ Not allowed
END IF;
END LOOP;
END;
/
Output / Error
ERROR at line 6: ORA-06550: line 6, column 7: PLS-00363: expression 'I' cannot be used as an assignment target ORA-06550: line 6, column 7: PL/SQL: Statement ignored
Why Does This Error Occur?
The error occurs because:
- The loop variable i is automatically managed by the FOR LOOP
- Oracle treats it as a constant within each iteration
- Assigning a value to it violates PL/SQL rules
Specifically:
- PLS-00363 → You cannot use the iterand as an assignment target
- ORA-06550 → General compilation error pointing to invalid PL/SQL syntax
Correct Approach
If you need to control or modify values during iteration, use a separate variable instead of modifying the iterand.
BEGIN
FOR i IN 1..3 LOOP
DECLARE
temp NUMBER;
BEGIN
temp := i;
IF temp = 3 THEN
temp := 2; -- ✅ Allowed
END IF;
DBMS_OUTPUT.PUT_LINE(temp);
END;
END LOOP;
END;
/
Key Takeaways
- FOR LOOP iterand is implicitly declared
- It is read-only inside the loop
- It is not accessible outside the loop
- Attempting to modify it results in PLS-00363 error
- Use a separate variable if modification is needed
Official Documentation
For more details on these errors, refer to Oracle documentation:
Conclusion
The FOR LOOP iterand simplifies iteration in PL/SQL by automatically handling loop control. However, this convenience comes with restrictions — most importantly, the inability to modify the iterand. Understanding this behavior helps prevent common errors and leads to cleaner, more reliable PL/SQL code.
No comments:
Post a Comment