Using the GOTO Statement
DECLARE
total NUMBER(9) := 0;
counter NUMBER(6) := 0;
BEGIN
<<calc_total>>
counter := counter + 1;
total := total + counter * counter;
-- branch to print_total label when condition is true
IF total > 25000 THEN GOTO print_total;
ELSE GOTO calc_total;
END IF;
<<print_total>>
DBMS_OUTPUT.PUT_LINE('Counter: ' || TO_CHAR(counter) || ' Total: ' ||
TO_CHAR(total));
END;
/
The GOTO statement is an unconditional branch that will jump execution to the “label” identified in the statement. It is not used very often and some programmers claim you should never use the GOTO statement as it will make the code harder to understand and violates the structured programming paradigm. A label is defined in the code with double open and close brackets.
<< important_label >>
When a GOTO statement is encountered, program execution jumps to the code directly after the label, so there must be at least one line of code after the label. Likewise, the label must be in scope when the GOTO statement is encountered. This requirement makes the GOTO statement a lot less useful than it appears. For example the first GOTO statements below are in scope with the labels.
SQL> declare
2 n_numb number := &Number;
3 begin
4 if n_numb < 5 then goto small_number;
5 else goto large_number;
6 end if;
7
8 n_numb := 25; -- goto jumps this line.
9
10 <<small_number>>
11 dbms_output.put_line ('Small Number.');
12 goto end_message;
13
14 <<large_number>>
15 dbms_output.put_line ('Large Number.');
16 goto end_message;
17
18 n_numb := 0; -- goto jumps this line.
19
20 <<end_message>>
21 dbms_output.put_line ('The End.');
22
23 end;
24 /
Enter value for number: 4
Small Number.
The End.
SQL> /
Enter value for number: 7
Large Number.
The End.
However, the example below shows that objects declared within the IF statements are out of scope to the outside block of code.
SQL> declare
2 n_num number := 5;
3 begin
4 goto then_clause;
5 if n_num < 8
6 then
7 <<then_clause>>
8 n_num := 8;
9 end if;
10 end;
11 /
goto then_clause;
*
ERROR at line 4:
ORA-06550: line 4, column 3:
PLS-00375: illegal GOTO statement ;
this GOTO cannot branch to label
'THEN_CLAUSE'
ORA-06550: line 6, column 5:
PL/SQL: Statement ignored
Jumping out of the IF statement in the first example is allowed because the label is in scope. Jumping into an IF statement in the second example is not allowed because the label is not in scope. This is also true for LOOPs, CASE statements, and PL/SQL exceptions. Likewise, a label in a function or procedure is not in scope to the calling block.
0 comments:
Post a Comment