Showing posts with label Loops. Show all posts
Showing posts with label Loops. Show all posts

Thursday, June 24, 2010

New in 11g: Continue and Continue When

CONTINUE immediately moves to the next iteration of the loop.
CONTINUE WHEN conditionally moves to the next iteration of the loop.
BEGIN 
  FOR idx IN 1..3 
  LOOP 
    dbms_output.PUT_LINE('-----------------------------------'); 
    dbms_output.PUT_LINE('Idx ' 
    ||idx 
    ||': BeFore Continue. Mod(Idx,2) = ' 
    ||MOD(idx,2)); 
    --------------------------------------------------- 
    --    If Mod(i,2) = 0 THEN --{ This is the 
    --        Continue;        -- same as the 
    --    End If;              -- Continue When below.} 
    --------------------------------------------------- 
    CONTINUE 
  WHEN MOD(idx,2) = 0; 
    dbms_output.PUT_LINE ('After Continue. Print If Mod(Idx,2) is not 0.'); 
  END LOOP; 
END;
/
Notes:
  • When using CONTINUE in a simple loop, make sure you increment your loop before the CONTINUE so you don't create an infinite loop.
  • When using CONTINUE in a While loop, try using a GOTO and a label.
  • Inlining impacts every call to CONTINUE and CONTINUE WHEN.

Tuesday, March 3, 2009

For Loop to Read Records in Cursor

--+----------------------------------------------------
--| Declaration Section - Define Department Stats
--+----------------------------------------------------
Declare

Cursor c_DeptStats Is
Select DName
, Count(*) EmpCnt
From Dept d, Emp e
Where d.Deptno = e.Deptno
Group By DName
Order By DName;
--+----------------------------------------------------
--| Execution: Loop to read records in cursor
--+----------------------------------------------------
Begin
For v_Rec In c_DeptStats Loop
---------------------------------------------------
If v_Rec.EmpCnt > 4 Then
Dbms_Output.Put_Line (v_Rec.DName ||' Has ' ||
v_Rec.EmpCnt||' Employees.');
End If;
---------------------------------------------------
End Loop;
End;
/

Embedded Select in For Loop

For v_Ctr in (Select DName, DeptNo From Dept)
Loop
...executable statements...
End Loop;

Labeling Loops

Begin
/*--------------------------------------------*/
<< l_Outer >>

For v_1Ctr In 1..5 Loop
...
/*-----------------------------------------*/
<< l_Inner >>

For v_2Ctr In 1..20 Loop
...
If v_1Ctr = 4
Then Exit l_Outer; -- Exits Both Loops
End If;

End Loop l_Inner;
/*-----------------------------------------*/
End Loop l_Outer;
/*--------------------------------------------*/

End;
/

Loops

Declare
v_Ctr Binary_Integer := 1;

Begin
While v_Ctr < 5 Loop
Do Something
v_Ctr := v_Ctr + 1;
End Loop;


Declare
v_Ctr Binary_Integer := 1;
v_Max Binary_Integer := &Max_Value;

Begin
Loop
Do Something
v_Ctr := v_Ctr + 1;
Exit When v_Ctr > v_Max;
End Loop;


/* v_Ctr Is Implicitly Declared As Binary_Integer. */
/* Can be a variable */
Begin
For v_Ctr In 1..Least(CtrA, CtrB) Loop
Do Something
End Loop;