Search code examples
sqloracle-databaseloopsplsqlprocedure

how to exit the procedure if condition met in a loop PL SQL


Let's say I have a for loop

for i in array.first .. array.last loop
 boolean := c(i) > d(i);
 if boolean --is true then
 exit the loop immediately and also exit the entire procedure

 else if the boolean is never true til the end of the loop, exit the loop
 and keep running other scripts in this procedure.

I know the 'EXIT' keyword needs to be inside of the loop in order to exit the loop if condition is met. And 'RETURN' needs to be outside of the loop, to exit the procedure.

But if I put 'RETURN' outside of the loop, then I think no matter what the result is from the loop, it will exit the entire procedure when the loop ends?


Solution

  • If you want to be didactic about it, you should use an EXIT to get out of the loop, then use a RETURN to exit from the procedure (duplicating any necessary tests), thus following the structured programming rule that "A procedure should only have a single entrance and a single exit". In practice 99.999% of programmers would just code the RETURN inside the body of the loop because A) it's clearer as to what's going on (you're not just getting out of the loop, you're returning from the procedure), and B) it's shorter. Do as you will. Best of luck.