
- PL/SQL Tutorial
- PL/SQL - Home
- PL/SQL - Overview
- PL/SQL - Environment
- PL/SQL - Basic Syntax
- PL/SQL - Data Types
- PL/SQL - Variables
- PL/SQL - Constants and Literals
- PL/SQL - Operators
- PL/SQL - Conditions
- PL/SQL - Loops
- PL/SQL - Strings
- PL/SQL - Arrays
- PL/SQL - Procedures
- PL/SQL - Functions
- PL/SQL - Cursors
- PL/SQL - Records
- PL/SQL - Exceptions
- PL/SQL - Triggers
- PL/SQL - Packages
- PL/SQL - Collections
- PL/SQL - Transactions
- PL/SQL - Date & Time
- PL/SQL - DBMS Output
- PL/SQL - Object Oriented
- PL/SQL Useful Resources
- PL/SQL - Questions and Answers
- PL/SQL - Quick Guide
- PL/SQL - Useful Resources
- PL/SQL - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PL/SQL - Basic Loop Statement
Basic loop structure encloses sequence of statements in between the LOOP and END LOOP statements. With each iteration, the sequence of statements is executed and then control resumes at the top of the loop.
Syntax
The syntax of a basic loop in PL/SQL programming language is −
LOOP Sequence of statements; END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT statement or an EXIT WHEN statement is required to break the loop.
Example
DECLARE x number := 10; BEGIN LOOP dbms_output.put_line(x); x := x + 10; IF x > 50 THEN exit; END IF; END LOOP; -- after exit, control resumes here dbms_output.put_line('After Exit x is: ' || x); END; /
When the above code is executed at the SQL prompt, it produces the following result −
10 20 30 40 50 After Exit x is: 60 PL/SQL procedure successfully completed.
You can use the EXIT WHEN statement instead of the EXIT statement −
DECLARE x number := 10; BEGIN LOOP dbms_output.put_line(x); x := x + 10; exit WHEN x > 50; END LOOP; -- after exit, control resumes here dbms_output.put_line('After Exit x is: ' || x); END; /
When the above code is executed at the SQL prompt, it produces the following result −
10 20 30 40 50 After Exit x is: 60 PL/SQL procedure successfully completed.
plsql_loops.htm
Advertisements