Adms Lab 7
Adms Lab 7
SAQIB MAHMOOD
460430
Class: BSCS-13
Objectives
The objective of this Lab is to understand the basics of Looping statements in PL/SQL.
Tools/Software Requirement
SQL Developer
VSCode
or you can directly run your commands in
https://livesql.oracle.com/next/
Description
PL/SQL provides different types of loops to repeatedly execute a block of statements. Loops are
fundamental in automating repetitive tasks, processing data sets, and performing iterative
calculations.
Types of Loops in PL/SQL
1. Basic Loop
2. WHILE Loop
3. FOR Loop
4. Nested Loops
Example
DECLARE
counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
EXIT WHEN counter > 5;
END LOOP;
END;
CS236: Advance Database Systems Page 2
While loop
The WHILE loop evaluates a condition before executing the loop’s body. If the condition is
TRUE, the loop executes; if it’s FALSE, the loop terminates.
Example
DECLARE
counter NUMBER := 1;
BEGIN
WHILE counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
END LOOP;
END;
For Loop
The FOR loop is used when the number of iterations is known in advance. It automatically
increments the loop counter.
Example
BEGIN
FOR counter IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
END LOOP;
END;
Nested Loops
Loops can be nested inside one another to perform complex iterations over multi-dimensional data.
Example
BEGIN
FOR i IN 1..3 LOOP
FOR j IN 1..2 LOOP
DBMS_OUTPUT.PUT_LINE('i = ' || i || ', j = ' || j);
END LOOP;
END LOOP;
END;
CODE:
DECLARE
-- Declare the cursor
CURSOR emp_cursor IS
SELECT FIRST_NAME, LAST_NAME , SALARY FROM EMPLOYEES;
BEGIN
-- Open the cursor
OPEN emp_cursor;
CODE:
DECLARE
-- Declare the cursor
CURSOR job_cursor IS
SELECT JOB_TITLE, MAX_SALARY FROM JOBS;
job_title JOBS.JOB_TITLE%TYPE;
max_salary JOBS.MAX_SALARY%TYPE;
highest_salary JOBS.MAX_SALARY%TYPE := 0;
highest_salary_job JOBS.JOB_TITLE%TYPE;
END IF;
END LOOP;
OUTPUT:
CODE:
DECLARE
-- Declare the cursor
CURSOR emp_cursor IS
SELECT EMPLOYEES.EMPLOYEE_ID,
EMPLOYEES.FIRST_NAME,
EMPLOYEES.LAST_NAME,
JOB_HISTORY.JOB_ID,
TRUNC(MONTHS_BETWEEN(JOB_HISTORY.END_DATE, JOB_HISTORY.START_DATE))
AS JOB_DURATION
FROM EMPLOYEES
JOIN JOB_HISTORY ON EMPLOYEES.EMPLOYEE_ID = JOB_HISTORY.EMPLOYEE_ID;
BEGIN
-- Open the cursor
OPEN emp_cursor;
OUTPUT:
Deliverables:
Submit a PDF document including the SQL queries to answer above-mentioned information needs
as well as snapshot of their outcome when executed over MySQL using the Workbench.