pl-sql
  1. pl-sql-goto

GOTO - (PL/SQL Control Statements)

In PL/SQL, the GOTO statement is used to transfer control to another part of the program. It is often used to exit a loop or block of code when a condition is met, or to skip over certain blocks of code based on a condition.

Syntax

The syntax for the GOTO statement in PL/SQL is as follows:

GOTO label;

Here, label is the name of the statement or block of code that you want to transfer control to.

Example

DECLARE
  counter NUMBER := 1;
BEGIN
  LOOP
    counter := counter + 1;
    IF counter > 10 THEN
      GOTO end_loop;
    END IF;
    dbms_output.put_line('Counter: ' || counter);
  END LOOP;
  <<end_loop>>
  dbms_output.put_line('Loop ended');
END;

Output

Counter: 2
Counter: 3
Counter: 4
Counter: 5
Counter: 6
Counter: 7
Counter: 8
Counter: 9
Counter: 10
Loop ended

Explanation

In the above example, we have a loop that increments the counter variable by 1 on each iteration. If the counter variable is greater than 10, the control is transferred to the end_loop label using the GOTO statement. We then print a message to indicate that the loop has ended.

Use

The GOTO statement can be useful in situations where you need to exit a loop or block of code based on a condition. However, it should be used sparingly as it can make code difficult to read and understand. In general, it is better to use other control structures like IF-ELSE, WHILE and FOR loops, or nested blocks instead of using GOTO.

Important Points

  • The GOTO statement is used to transfer control to another part of the program.
  • It should be used with caution as it can make code difficult to read and understand.
  • It is generally better to use other control structures like IF-ELSE, WHILE and FOR loops, or nested blocks instead of using GOTO.

Summary

In summary, the GOTO statement in PL/SQL is used to transfer control to another part of the program. However, it should be used sparingly and with caution as it can make code difficult to read and understand. Other control structures like IF-ELSE, WHILE and FOR loops, or nested blocks are generally preferred over GOTO.

Published on: