Iñaki Guastalli
Iñaki Guastalli

Reputation: 167

Exiting prematurelly a FOR from an internal IF

I've been browsing a while but I haven't found a successful answer for this.. shouldn't be much trouble for an experienced SQL coder:

I have the following FOR loop with an IF condition inside, and I want to exit the loop whenever the IF condition is met

<<OUTER_LOOP>>
FOR I IN T_TITLE.FIRST.. T_TABLE.LAST LOOP
  IF T_TABLE(I).VAR_TITLE = PAR_TITLE THEN
    V_TITLE_ID = I;
    --insert exit here
  END IF;
END LOOP;

I'm uncertain whether to use EXIT; EXIT OUTER_LOOP; or something like EXIT OUTER_LOOP WHEN V_TITLE_ID IS NOT NULL;

Thanks a lot for the help!

Upvotes: 0

Views: 37

Answers (1)

Przemyslaw Kruglej
Przemyslaw Kruglej

Reputation: 8123

Just use EXIT:

FOR I IN T_TITLE.FIRST.. T_TABLE.LAST LOOP
  IF T_TABLE(I).VAR_TITLE = PAR_TITLE THEN
    V_TITLE_ID = I;
    EXIT;
  END IF;
END LOOP;

You shouldn't use EXIT WHEN in this situation, because you wouldn't be able to save the value of I.

You could use EXIT some_loop_label, but it is not necessary in your situation. It may come in handy when you have nested loops, though.

More information here: EXIT in Oracle

Upvotes: 2

Related Questions