sqloracle-databasefor-loopplsqllabel

Oracle PL SQL: using labels to get out of for loops


SET SERVEROUTPUT ON
BEGIN
  <<outer_loop>>
  FOR i IN 1..10 LOOP
    FOR i IN 1..3 LOOP
      EXIT outer_loop WHEN outer_loop.i = 3;
    DBMS_OUTPUT.PUT_LINE('outer i is:' || outer_loop.i || ' inner i is: ' ||i);
      GOTO goodbye;
    END LOOP;       
  END LOOP;
  <<goodbye>>
  NULL;
END;
/

I have the code above and it gives the result below, but my notes say to NEVER do this. Why is this the case? It does work after all.

anonymous block completed
outer i is:1 inner i is: 1

Solution

  • The GOTO is considered as poor programming practice. It came from old times when older programming languages didn't have a lot of structure and programmers were forced to use a lot of GOTO.

    The GOTO leads to what is known as spaghetti code. It's hard to read and hard to understand.