DB-PLSQL Key-1-1
DB-PLSQL Key-1-1
Execution Block
The execution block is the part of the PL/SQL block where the actual logic and statements to
be executed are written.
Basic Block Structure
The simplest PL/SQL block does nothing. You must have a minimum of one statement inside
any execution block, even if it’s a NULL statement.
Declaration Block
The declaration block is an optional section that is used to define and initialize variables,
constants, cursors, and subprograms required in the execution block.
1. Anonymous Blocks
An anonymous block is an unnamed PL/SQL block that is not stored in the database and
executes immediately.
Variable Behavior:
• Variables are local to the block.
• They exist only during execution and cannot be accessed outside the block.
Example:
sql
CopyEdit
BEGIN
DECLARE message VARCHAR2(50) := 'Hello, Anonymous Block!';
BEGIN
DBMS_OUTPUT.PUT_LINE(message); -- Accessible within the block
END;
-- message is not accessible here
END;
1. BULK COLLECT
• Retrieves multiple rows in a single fetch and stores them in a collection (e.g.,
VARRAY, TABLE, or RECORD).
• Reduces context switching between SQL and PL/SQL, improving performance.
COMMIT;
END;
• Minimizes SQL context switching, leading to faster execution.
B. Nested Tables
• Can be stored in the database and used in SQL queries.
• Allows deleting and reordering elements.
Example:
sql
CopyEdit
DECLARE
TYPE num_table IS TABLE OF NUMBER;
numbers num_table := num_table(10, 20, 30);
BEGIN
DBMS_OUTPUT.PUT_LINE('First Number: ' || numbers(1));
END;
/
Summary
Composite Type Characteristics Use Case
Holds different data types in a structured Used for processing table row
RECORD
format data
Associative Used for fast in-memory
Unbounded, indexed by numbers/strings
Array lookups
Composite Type Characteristics Use Case
Used for storing collections in
Nested Table Dynamic, stored in DB, can be sparse
tables
VARRAY Fixed size, stored in DB, dense Used for small, ordered data sets
2. Nested Tables
• Usage: Can store in the database as a column, supports dynamic resizing.
• Sparsity: Can have gaps between indexes.
Example:
sql
CopyEdit
DECLARE
TYPE emp_id_table IS TABLE OF NUMBER;
emp_ids emp_id_table := emp_id_table();
BEGIN
emp_ids.EXTEND(3);
emp_ids(1) := 101;
emp_ids(2) := 102;
emp_ids(3) := 103;
FOR i IN 1..emp_ids.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_ids(i));
END LOOP;
END;
Useful for database storage and dynamic data handling.
16. Explain the use of Object Types (Varry and Table Collections) in
PL/SQL.
ANS:
Use of Object Types (VARRAY and Table Collections) in PL/SQL
PL/SQL object types allow structured data storage and manipulation. VARRAYs and Table
Collections (Nested Tables) are used to store multiple values of the same data type
efficiently. They enhance performance, flexibility, and modularity in database operations.
Use Cases:
• Storing Lookup Tables (e.g., Employee ID → Name).
• Fast Data Processing in Memory.
• Session-based Data Caching for quick access.
A PL/SQL Procedure is a named block that performs a specific task and can be executed
multiple times. It does not return a value but can take IN, OUT, or IN OUT parameters.
1. Structure of a PL/SQL Procedure
A procedure consists of four main parts:
Header – Defines the procedure name and parameters.
Declarative Section (Optional) – Declares variables, cursors, or record structures.
Execution Section (Mandatory) – Contains SQL and PL/SQL statements.
Exception Handling (Optional) – Manages errors using predefined exceptions.
Syntax:
CREATE OR REPLACE PROCEDURE procedure_name (param1 IN datatype, param2 OUT
datatype)
IS
var_name datatype;
BEGIN
-- SQL Statements and Business Logic
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error Occurred');
END procedure_name;
/
2. Example: Insert Employee Record
CREATE OR REPLACE PROCEDURE add_employee (
p_emp_id IN NUMBER,
p_name IN VARCHAR2,
p_salary IN NUMBER)
IS
BEGIN
INSERT INTO employees (emp_id, name, salary)
VALUES (p_emp_id, p_name, p_salary);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END add_employee;
/
Calling the Procedure:
EXEC add_employee(101, 'John Doe', 50000);
3. Key Features of Procedures
Modularity – Encourages reusability and better organization.
Performance – Reduces network traffic by executing as a single unit.
Security – Restricts direct table access by encapsulating logic.
Error Handling – Ensures smooth execution with exception handling.
4. Procedure vs. Function
Feature Procedure Function
Returns Value No Yes
Used in SQL Queries No Yes
Supports DML Operations Yes No (with exceptions)
B. Package Body
Implements the logic for procedures and functions.
Can have private components that are not accessible outside the package.
Syntax:
CREATE OR REPLACE PACKAGE BODY package_name AS
PROCEDURE proc_name IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Procedure Executed');
END proc_name;
Package Body:
CREATE OR REPLACE PACKAGE BODY emp_pkg AS
PROCEDURE add_employee(p_id NUMBER, p_name VARCHAR2, p_salary NUMBER)
IS
BEGIN
INSERT INTO employees(emp_id, name, salary) VALUES (p_id, p_name, p_salary);
COMMIT;
END add_employee;
Let's compare these two methods in terms of how they work and when they are useful.
Timestamp-based Validation
Timestamp-based validation relies on comparing the timestamp (last modification time) of
the dependent object and the objects it relies on (such as tables, views, or other packages). If
the dependent object has a later timestamp than the object it depends on, the object is
considered out of date or invalid and requires recompilation.
Example:
You can view the last compiled time of an object with a query like this: SELECT
object_name, last_ddl_time
FROM user_objects
WHERE object_type IN ('PACKAGE', 'FUNCTION', 'PROCEDURE')
AND object_name = 'MY_PACKAGE';
Signature-based Validation
Signature-based validation involves comparing the signature of a PL/SQL object to see if it
matches its previous version. The signature includes the interface of the object, such as the
procedure's name, parameters, return type, and the names of functions. Essentially, the
signature represents the “contract” of the object, and any change to this contract (such as
changing the number or types of parameters in a function) would invalidate the object.
Example:
Suppose you have a function:
CREATE OR REPLACE FUNCTION calculate_tax (p_salary NUMBER) RETURN
NUMBER IS BEGIN
RETURN p_salary * 0.1; END calculate_tax;
If you change the parameter (e.g., rename p_salary to p_income), the signature of the function
changes, and Oracle will mark the function as invalid even if the timestamp remains
unchanged.
You can view the signature of an object by querying the USER_PROCEDURES or
USER_FUNCTIONS views, and checking for changes in the parameters:
SELECT object_name, procedure_name, parameter_name FROM user_procedures
WHERE object_name = 'MY_PACKAGE';
4. Conclusion
The PL/SQL trigger architecture ensures automatic execution when specific events occur,
helping maintain data consistency, security, and automation in database systems.
28. Discuss the different types of DML Triggers and their use cases?
Ans
Types of DML Triggers and Their Use Cases
DML (Data Manipulation Language) triggers are special procedures that automatically
execute when a DML operation (INSERT, UPDATE, DELETE) occurs on a table in a
database. They help enforce business rules, maintain data integrity, and automate processes.
1. AFTER Triggers (Post-Trigger)
Executed after a DML operation is completed.
Used for logging changes or auditing data modifications.
Use Case:
An INSTEAD OF trigger is a special type of trigger in Oracle that allows you to replace the default
DML action (such as INSERT, UPDATE, or DELETE) with custom logic. These triggers are
commonly used with views to perform DML operations on underlying base tables when users interact
with the view, essentially providing a mechanism to perform actions on a virtual layer rather than
directly on the physical data structure.
Let's say you have a view that combines data from two tables: employees and departments. You want to
allow users to insert data into the view, but when they do, the trigger should insert data into the correct
base tables.
Now, you create an INSTEAD OF trigger that redirects INSERT operations on the employee_view to
the underlying employees and departments tables.
BEGIN
SELECT department_id INTO v_department_id FROM departments
WHERE department_name = :NEW.department_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- If department doesn't exist, insert a new department INSERT INTO departments
(department_name) VALUES (:NEW.department_name);
-- Get the new department_id SELECT department_id INTO v_department_id FROM
departments
WHERE department_name = :NEW.department_name; END;
The trigger will handle the INSERT operation by adding data to both the employees and
departments tables as needed.
One of the most common errors encountered with triggers is the mutating table error. This
occurs when a trigger attempts to modify the same table that fired the trigger.
Mutating Table
A mutating table refers to a table that is in the process of being modified by a DML operation
(such as INSERT, UPDATE, or DELETE). If a trigger attempts to query or modify the same
table during this operation, Oracle cannot guarantee that the data will be consistent.
Consider a scenario where you have a trigger that fires AFTER UPDATE on the employees
table and attempts to query the employees table to check the old and new values of certain
columns.
This will raise a mutating table error because the trigger tries to query the employees table
while an UPDATE operation is already happening on it.
Solution:a
Use a BEFORE trigger or AFTER statement-level trigger to work with the entire table
rather than specific rows.
Use a temporary table or collection to store values during the trigger and access them later.
When performing an UPDATE on multiple rows in a table, a row-level trigger will fire for each row
affected by the UPDATE.