Week 3 - Handling Data in PLSQL Block
Week 3 - Handling Data in PLSQL Block
www.vut.ac.za
Vivian Mapande
1
www.vut.ac.za
CONTENTS
1. Use SQL queries in a PL/SQL executable block
3. Make use of the INTO clause to hold the values returned by a SQL statement
• It refers to the ability to include SQL statements within a PL/SQL block of code.
• PL/SQL allows for the execution of SQL statements along with the ability to incorporate programming
constructs such as variables, loops, conditionals, and exception handling.
• The key point to note is that the SQL query is embedded within the PL/SQL block using the appropriate
syntax. The result of the SQL query can be stored in PL/SQL variables, used in conditional statements,
or even used to perform DML (Data Manipulation Language) operations.
3
Basic PL/SQL block structures
5
Basic PL/SQL block structures
COMMIT;
END;
6
Basic PL/SQL block structures
COMMIT;
END;
7
Basic PL/SQL block structures
Make use of the INTO clause to hold the values returned by a SQL statement
• The INTO clause is used to store the result of a SELECT query into a set of variables or a single variable.
• It is a way to fetch a single row or a single column value from a SQL query and assign it to a variable.
• Here is an example to better understand the usage of the INTO clause:
• Let's say we have a table called "Employees" with columns "employee_id" and "employee_name".
Suppose we want to retrieve the name of an employee based on their ID:
DECLARE
v_employee_name Employees.employee_name%TYPE; -- declare a variable to hold the employee name
BEGIN
SELECT employee_name INTO v_employee_name -- use the INTO clause to store the employee name
FROM Employees
WHERE employee_id = 1; -- assuming the employee ID is 1
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_employee_name); -- printing the employee name
END;
8
Basic PL/SQL block structures
9
Basic PL/SQL block structures
1
0
Basic PL/SQL block structures
1
1
Basic PL/SQL block structures
1
2
Basic PL/SQL block structures
COMMIT;
END;
/
When using record variable:
• First declare a record type called "employee_record" that defines the structure of the record variable
"emp". It has four fields: employee_id (NUMBER), first_name (VARCHAR2), last_name (VARCHAR2), and
hire_date (DATE).
1
3
Basic PL/SQL block structures
• Finally, we use the record variable in an INSERT statement to insert the data into an "employees" table.
Note that we can directly reference the fields of the record variable in the INSERT statement
(emp.field_name).
1
4