Unit 4
Unit 4
Basics of PL/SQL
Advantages of Pl/SQL
• PL/SQL is tightly integrated with SQL, enabling seamless access to Oracle databases,
allowing developers to manipulate data efficiently and handle complex SQL
operations.
2. Improved Performance
• PL/SQL allows block processing, where multiple SQL statements are executed in a
single go, reducing the context switches between the SQL and PL/SQL engines,
resulting in better performance for operations like batch processing.
3. Error Handling
• PL/SQL has robust exception handling mechanisms, making it easier to detect and
manage errors during runtime. This reduces the chances of runtime failures and makes
it easier to debug applications.
4. Portability
• PL/SQL code can run on any Oracle database, making it portable across different
operating systems and hardware platforms, as long as the environment supports
Oracle databases.
5. Encapsulation of Business Logic
• PL/SQL supports modular programming through the use of functions, procedures, and
packages. This allows for code reuse and a more organized approach to development.
7. Security
• Since PL/SQL can execute multiple SQL statements as a block, it reduces the amount
of network traffic between the application and the database, which improves
performance in distributed systems.
• PL/SQL supports the creation of database triggers, which can automatically invoke
certain actions when specific conditions are met, enhancing automation and
consistency within the database.
Disadvantages of Pl/SQL
1. Oracle Dependency
• PL/SQL can be complex for beginners, especially for developers who are not familiar
with procedural programming. Its syntax and structure can be difficult to master
compared to other, more modern languages.
• While PL/SQL is optimized for database operations, it may not perform as well for
very complex computational tasks when compared to languages like Java, Python, or
C++, which are better suited for heavy computation.
4. Limited Support for Advanced Programming Concepts
• PL/SQL lacks support for some advanced programming concepts like multi-threading
and object-oriented programming, which can be restrictive when building more
complex applications.
5. Platform Boundaries
• PL/SQL is generally used within Oracle databases. As a result, the application logic
written in PL/SQL is bound to the database layer. This can be problematic in
distributed systems where application logic is spread across multiple services and
platforms.
6. Execution Speed
• While PL/SQL is fast for database-related tasks, its execution speed for general-
purpose programming tasks (such as heavy number crunching, complex algorithms,
etc.) is slower compared to languages specifically designed for those tasks.
• Although PL/SQL has a robust error handling mechanism, managing exceptions can
become cumbersome in large applications. Developers need to be careful when
writing exception handlers, as improper handling can lead to code that is difficult to
debug and maintain.
Ans –
SQL PL/SQL
Ans –
PL/SQL follows a block structure that allows developers to organize and manage code
efficiently. The block structure divides code into logical sections, making it easy to read,
maintain, and debug. A PL/SQL block is typically composed of the following sections:
1. Declaration Section
• This section is where you declare variables, cursors, constants, exceptions, and other
data types.
• It begins with the DECLARE keyword.
• It is optional, meaning you can omit this section if there are no declarations needed.
Example:
DECLARE
v_employee_name VARCHAR2(50);
v_salary NUMBER := 5000;
2. Execution Section
• This is the main section of the PL/SQL block where the program logic is written.
• It contains SQL statements, control statements (loops, conditions), and any other
procedural code.
• It begins with the BEGIN keyword and ends with the END keyword.
• This section is mandatory, and at least one executable statement must be present.
Example:
BEGIN
v_employee_name := 'John Doe';
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_employee_name);
• This section is used to handle errors or exceptions that occur during the execution of
the block.
• It begins with the EXCEPTION keyword.
• It is optional but highly recommended, especially in production environments, to
handle potential runtime errors.
Example:
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No records found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred.');
Q) Explain Data types, Variable and Constant in PL/SQL.
Ans –
A data type defines the kind of data a variable can hold, such as numbers, characters, dates,
or complex structures like records and collections. PL/SQL supports a variety of data types,
categorized into the following groups:
• NUMBER:
o Stores numeric data, including integers and floating-point numbers.
o Example: NUMBER(5,2) represents a number with 5 digits, of which 2 digits
are after the decimal point.
• VARCHAR2:
o Stores variable-length alphanumeric strings (up to 32,767 bytes).
o Example: VARCHAR2(50) can store a string up to 50 characters.
• CHAR:
o Stores fixed-length alphanumeric strings.
o Example: CHAR(10) always stores 10 characters, padding with spaces if
necessary.
• DATE:
o Stores date and time values.
o Example: DATE can store values like '21-SEP-2024 12:00:00'.
• BOOLEAN:
o Stores TRUE, FALSE, or NULL values.
o Example: BOOLEAN is useful in control flow logic.
• BLOB:
o Stores binary large objects, such as images or files.
o Example: BLOB can store large amounts of binary data.
• CLOB:
o Stores large text data (Character Large Object).
o Example: CLOB is used for storing large text files or long descriptions.
• RECORD:
o A composite data type that can group several fields of different types.
o Example: A RECORD can be used to store an employee’s name, salary, and
date of hire in a single structure.
• TABLE:
o A collection data type that stores multiple elements of the same type, similar to
arrays.
o Example: TABLE can store a list of numbers or strings.
Variables in PL/SQL
A variable is a named storage location in memory that can hold a value during the execution
of a PL/SQL block. Variables are declared in the declaration section of a PL/SQL block, and
their values can change during execution.
here,
Constants in PL/SQL
A constant is similar to a variable, but once a constant is initialized, its value cannot be
changed during the execution of the program. Constants are used when you need to represent
fixed values, such as mathematical constants (e.g., PI) or configuration parameters.
here,
PL/SQL provides various control structures to manage the flow of program execution.
These control structures are categorized into three main types: Conditional Control,
Iterative Control, and Sequential Control. Each of these structures plays a specific role in
controlling how PL/SQL code is executed.
Conditional control in PL/SQL refers to the ability to execute different blocks of code based
on the evaluation of specific conditions. It allows for decision-making in programs, enabling
the execution of certain statements when particular conditions are met and skipping or
executing alternative statements when conditions are not met. Conditional control structures
make the program dynamic by controlling the flow of execution based on real-time data.
1. IF-THEN Statement
The IF-THEN statement is the simplest form of conditional control in PL/SQL. It is used to
execute a block of code only if a specified condition evaluates to TRUE. If the condition is
FALSE, the block of code is skipped, and the program continues with the next statement after
the IF block.
Syntax:
IF condition THEN
-- Block of statements to execute if the condition is
TRUE END IF;
Flow Diagram
Example:
DECLARE
v_salary NUMBER := 5000;
BEGIN
IF v_salary > 4000 THEN
DBMS_OUTPUT.PUT_LINE('Salary is greater than 4000');
END IF;
END;
2. IF-THEN-ELSE Statement
The IF-THEN-ELSE statement extends the basic IF-THEN statement by adding an ELSE
clause. This allows the execution of an alternative block of code if the condition evaluates to
FALSE. Therefore, depending on whether the condition is true or false, one of two possible
blocks will be executed.
Syntax:
IF condition THEN
-- Block of statements if the condition is TRUE
ELSE
-- Block of statements if the condition is FALSE
END IF;
Flow Diagram
Example:
DECLARE
v_salary NUMBER := 3000;
BEGIN
IF v_salary > 4000 THEN
DBMS_OUTPUT.PUT_LINE('Salary is greater than 4000');
ELSE
DBMS_OUTPUT.PUT_LINE('Salary is less than or equal to 4000');
END IF;
END;
3. IF-THEN-ELSIF Statement
The IF-THEN-ELSIF statement is used when there are multiple conditions to be checked
sequentially. If the first condition is not satisfied, the next condition is checked, and so on.
Once a condition evaluates to TRUE, the associated block of code is executed, and the
remaining conditions are ignored. If none of the conditions are TRUE, an optional ELSE
block can be executed.
Syntax:
IF condition1 THEN
-- Block of statements if condition1 is TRUE
ELSIF condition2 THEN
-- Block of statements if condition2 is TRUE
ELSE
-- Block of statements if no conditions are TRUE
END IF;
Flow Diagram
Example:
DECLARE
v_grade CHAR(1) := 'B';
BEGIN
IF v_grade = 'A' THEN
DBMS_OUTPUT.PUT_LINE('Excellent');
ELSIF v_grade = 'B' THEN
DBMS_OUTPUT.PUT_LINE('Good');
ELSE
DBMS_OUTPUT.PUT_LINE('Needs Improvement');
END IF;
END;
Iterative control in PL/SQL is a mechanism that allows the execution of a block of code
repeatedly based on specified conditions. Iteration is essential in programming to handle
repetitive tasks, loops, or cycles where a set of operations must be performed multiple times.
In PL/SQL, iterative control structures are used to manage the flow of execution in a block of
code, enabling developers to control how many times a certain sequence of statements is
executed. The loop continues until a condition is met or the loop is explicitly exited. These
iterative structures play a significant role in automating tasks such as updating records,
processing data in batches, or performing computations repeatedly until a particular condition
is satisfied.
1) Simple Loops
A simple loop is the most basic form of iteration. The loop continues indefinitely unless an
explicit EXIT statement is encountered. This loop provides maximum flexibility, as you can
control when and under what condition the loop should stop.
Example use case: Processing records from a cursor in an unknown number of iterations,
exiting the loop when the cursor has no more records to process.
Syntax:
LOOP
-- Sequence of statements
EXIT WHEN condition; -- Condition to exit the loop
END LOOP;
Flow Diagram
Example:
DECLARE
counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter is: ' || counter);
counter := counter + 1;
2) WHILE Loops
This loop checks a condition at the beginning of each iteration. If the condition evaluates to
TRUE, the loop’s body executes; otherwise, the loop terminates. It is used when the number
of iterations is unknown but is determined by a logical condition.
Example use case: Running a loop as long as a system resource remains available or until a
specific threshold is reached.
Syntax:
WHILE condition LOOP
-- Sequence of statements
END LOOP;
Flow Diagram
Example:
DECLARE
counter NUMBER := 1;
BEGIN
WHILE counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter is: ' || counter);
counter := counter + 1;
END LOOP;
END;
3) FOR Loops
A FOR loop is used to iterate over a specific range of values (both predefined or dynamically
generated). The loop automatically terminates after the iteration through the range is
complete. This type of loop is particularly useful when the number of iterations is known or
based on a set of data.
Example use case: Looping through an array, a set of database records, or a predefined range
of numbers.
Syntax:
FOR counter IN lower_bound..upper_bound LOOP
-- Sequence of statements
END LOOP;
Flow Diagram
Example:
BEGIN
FOR counter IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter is: ' || counter);
END LOOP;
END;
Sequential Control in PL/SQL
Sequential control in PL/SQL refers to the natural flow of control in a program, where
statements are executed one after another, in the order in which they are written. This type of
control does not involve any branching, looping, or conditional execution; rather, it follows a
linear execution path, making it the most basic form of control flow.
In PL/SQL, the sequential control flow is essential because it forms the foundation of any
PL/SQL block. As the name suggests, sequential control means that the execution progresses
step by step, and the next statement is executed only when the current one finishes. The flow
remains uninterrupted unless an error occurs or some other control structures (like conditional
or iterative control) are introduced.
Syntax:
DECLARE
-- Variable Declarations
variable1 datatype;
variable2 datatype;
BEGIN
-- Sequence of Statements executed one after another
statement1;
statement2;
statement3;
...
statementN;
END;
Flow Diagram
Example:
DECLARE
-- Declare variables
num1 NUMBER := 10;
num2 NUMBER := 20;
result NUMBER;
BEGIN
-- Sequential execution of statements
result := num1 + num2; -- Perform addition
DBMS_OUTPUT.PUT_LINE('The sum of num1 and num2 is: ' || result);
Ans-
Exception handling in PL/SQL is a mechanism used to detect, respond to, and recover from
runtime errors that occur during the execution of PL/SQL code. An exception is a runtime
event that can disrupt the normal flow of a program, such as an error condition (like a
division by zero, invalid data, or missing data). Exception handling allows the program to
gracefully manage these errors without abruptly terminating.
PL/SQL exceptions are raised when an error condition occurs, and PL/SQL provides a way to
"catch" these exceptions and take corrective action. Exception handling ensures that the
program does not fail entirely but instead follows an alternate path to handle the error.
1. Exception: A condition that causes the program to deviate from its normal flow.
2. Exception Handler: A block of code within the program that gets executed when an
exception is raised.
3. Raising an Exception: When an error occurs or an unusual condition is detected, an
exception is raised (either automatically by the system or manually by the user).
4. Handling an Exception: Once an exception is raised, control passes to the exception
handling section, where the program can either resolve the error or terminate
gracefully.
Syntax:
BEGIN
-- Executable statements
EXCEPTION
WHEN exception_name THEN
-- Handling statements for this exception
WHEN OTHERS THEN
-- Handling statements for all other exceptions
END;
Types of Exceptions
1. Predefined Exceptions
PL/SQL provides several predefined exceptions to handle common runtime errors. These
exceptions are raised automatically when specific error conditions occur. For example,
attempting to divide by zero, referencing a null value, or trying to fetch data that doesn’t exist
will raise predefined exceptions.
Common Predefined Exceptions:
BEGIN
-- Executable statements that might raise exceptions
EXCEPTION
-- Handle specific predefined exceptions
WHEN exception_name THEN
-- Code to handle the exception
statement;
WHEN exception_name_2 THEN
-- Code to handle another predefined exception
statement;
WHEN OTHERS THEN
-- Catch-all for any unhandled exceptions
statement;
END;
DECLARE
num1 NUMBER := 10;
num2 NUMBER := 0;
result NUMBER;
BEGIN
-- Division by zero error
result := num1 / num2;
DBMS_OUTPUT.PUT_LINE('Result: ' || result);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Division by zero is not allowed.');
END;
2. User-Defined Exceptions
User-defined exceptions are exceptions that are explicitly declared by the developer in the
DECLARE section of a PL/SQL block. These exceptions are raised manually when certain
conditions are met, which allows the developer to define custom error conditions specific to
the application logic.
DECLARE
-- Declare user-defined exception
ex_custom_exception EXCEPTION;
BEGIN
-- Raise the exception based on a condition
IF some_condition THEN
RAISE ex_custom_exception;
END IF;
EXCEPTION
-- Handle the user-defined exception
WHEN ex_custom_exception THEN
DBMS_OUTPUT.PUT_LINE('Custom Exception Raised and Handled.');
END;
DECLARE
salary NUMBER := 50000;
max_salary EXCEPTION; -- Declare a user-defined exception
BEGIN
-- Raise the custom exception if salary exceeds a certain limit
IF salary > 40000 THEN
RAISE max_salary; -- Trigger the custom exception
END IF;
EXCEPTION
-- Handle the user-defined exception
WHEN max_salary THEN
DBMS_OUTPUT.PUT_LINE('Error: Salary exceeds the allowed limit.');
END;
Ans –
Ans –
Oracle creates a memory area, known as the context area, for processing an SQL statement,
which contains all the information needed for processing the statement; for example, the
number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.
A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the
cursor holds is referred to as the active set.
DIAGRAM OF CURSOR
Types of Cursors:
1. Implicit Cursor:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the data that needs
to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,
designed for use with the FORALL statement. The following table provides the description of
the most used attributes −
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
2
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
3 automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
Example:
BEGIN
UPDATE employees
SET salary = salary * 1.1
WHERE department_id = 10;
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Rows updated: ' || SQL%ROWCOUNT);
ELSE
DBMS_OUTPUT.PUT_LINE('No rows were updated.');
END IF;
END;
2) Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It
is created on a SELECT Statement which returns more than one row.
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it. For example, we will open the above defined
cursor as follows −
OPEN c_customers;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows −
Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows −
CLOSE c_customers;
Example:
DECLARE
-- Declare a cursor to retrieve employee details
CURSOR emp_cursor IS
SELECT employee_id, first_name, salary FROM employees WHERE department_id = 10;
b) declaring of cursor
e) parameterized cursor
Ans –
In PL/SQL, when using explicit cursors, you must manually control the opening and closing
of the cursor. This process involves a series of operations to manage the cursor’s lifecycle,
ensuring efficient memory usage and avoiding resource leaks.
Here is the theoretical information about opening and closing an explicit cursor:
Once a cursor is opened, it remains open until explicitly closed, and you can begin fetching
rows from it.
Once you have finished fetching rows from the cursor, or when the cursor is no longer
needed, it should be closed to:
It is essential to close a cursor to free up system resources. Failing to close a cursor can lead
to resource leakage, which could eventually cause the database session to run out of available
cursors or memory.
b) declaring of cursor
n PL/SQL, a cursor is a pointer that allows you to retrieve and process multiple rows from a
SELECT query. When working with explicit cursors, the first step is to declare the cursor,
which defines the SQL query to be executed later. The declaration itself doesn’t execute the
query; it just establishes the query to be used when the cursor is opened.
CURSOR cursor_name IS
SELECT_statement;
• cursor_name: This is the name you give to the cursor. It must follow naming
conventions for PL/SQL identifiers.
• SELECT_statement: This is the SQL query that will retrieve data from the database
when the cursor is opened. The query can select multiple rows and can include any
valid SQL clauses (such as WHERE, ORDER BY, JOIN, etc.).
Example of Cursor Declaration:
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id = 10;
BEGIN
-- The cursor can be opened, fetched, and closed here
NULL;
END;
Once declare and open an explicit cursor in PL/SQL, the next step is to fetch records from
the cursor. The FETCH statement retrieves the next row from the result set of the cursor and
places it into predefined variables or a record.
• cursor_name: The name of the cursor from which you are fetching data.
• variable1, variable2, ...: Variables or a record to store the values fetched from the
cursor.
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id = 10;
A cursor FOR loop is a special kind of loop in PL/SQL that simplifies the process of
working with explicit cursors. It automatically handles the opening, fetching, and closing of
the cursor, eliminating the need for explicit OPEN, FETCH, and CLOSE statements. This
makes it easier and more efficient to work with cursors, especially when processing all rows
from the result set.
Implicit Handling: The cursor FOR loop opens the cursor, fetches each row into a
record or variables, and closes the cursor automatically after processing all rows.
Simplified Syntax: You do not need to manually declare loop variables, fetch
records, or close the cursor, as the loop manages all of this internally.
Record or Row Fetching: In a cursor FOR loop, each row from the cursor result set
is fetched into a record, and you can access the columns of the row using dot notation.
• record_name: The name of an implicit record that is created to hold the values of
each row fetched from the cursor.
• cursor_name: The name of the explicitly declared cursor.
DECLARE
-- Declare an explicit cursor
CURSOR emp_cursor IS
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id = 10;
BEGIN
-- Use a cursor FOR loop to fetch and process each row
FOR emp_record IN emp_cursor LOOP
-- Access the columns of the current row using dot notation
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_record.employee_id ||
', Name: ' || emp_record.first_name ||
', Salary: ' || emp_record.salary);
END LOOP;
END;
e) parameterized cursor
A parameterized cursor is a cursor that accepts parameters when it is opened, allowing you
to pass values dynamically to the cursor's query at runtime. This gives you the flexibility to
reuse the cursor for different values or conditions, making your code more dynamic and
efficient.
DECLARE
-- Declare a parameterized cursor that takes a department ID as a parameter
CURSOR emp_cursor (p_dept_id NUMBER) IS
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id = p_dept_id;
Ans –
A procedure in PL/SQL is a named block of code that performs a specific task or set of
actions. It is a subprogram that can be stored in the database and executed when needed.
Unlike functions, procedures do not return a value directly but can return multiple values
through OUT parameters.
1. Reusability: Procedures allow you to define logic once and reuse it whenever
necessary, promoting code reuse.
2. Encapsulation: A procedure encapsulates a block of PL/SQL code that performs a
specific action, keeping the implementation details hidden and making the program
easier to manage.
3. No Return Value: A procedure does not return a value like a function, but it can
return multiple values through OUT or IN OUT parameters.
4. Parameters:
o IN: Input parameters (pass data into the procedure).
o OUT: Output parameters (return data from the procedure).
o IN OUT: Parameters that can both accept input and return output.
1. Modularity: Procedures help break down complex code into smaller, manageable
parts.
2. Performance: Since procedures are stored in the database, they can be precompiled,
which improves performance.
3. Security: Procedures can encapsulate business logic and ensure that users cannot
access or manipulate data directly.
4. Maintainability: Procedures make it easier to update and maintain the code. Changes
can be made in one place, and all programs that call the procedure will use the
updated logic.
Ans –
A stored procedure in PL/SQL is a precompiled block of code that performs a specific task.
It is stored in the database and can be executed as needed. Stored procedures help modularize
code, improve performance, and enhance reusability. Unlike functions, stored procedures do
not return a value directly, but they can accept and return multiple values via parameters.
To create a stored procedure, you use the CREATE OR REPLACE PROCEDURE statement.
The procedure contains a name, parameters, and a PL/SQL block that defines the logic.
Syntax:
CREATE OR REPLACE PROCEDURE procedure_name (parameter1 datatype, parameter2
datatype, ...) IS
BEGIN
-- PL/SQL block with statements to execute
-- Logical operations or database operations
END procedure_name;
Components:
Example:
• This procedure accepts an employee ID (p_emp_id) and retrieves the salary of the
employee from the employees table, printing it to the console.
After creating a procedure, you can execute it using an anonymous PL/SQL block (BEGIN
... END;). The procedure is called using its name and passing any required parameters.
Syntax:
BEGIN
procedure_name(parameter1, parameter2, ...);
END;
/
Components:
Example:
BEGIN
get_salary(101);
END;
/
This will output the salary of the employee with ID 101 to the console using
DBMS_OUTPUT.PUT_LINE.
If you no longer need a stored procedure, you can delete it from the database using the DROP
PROCEDURE statement. This removes the procedure and all associated metadata from the
database.
Syntax:
DROP PROCEDURE procedure_name;
Components:
Ans –
A function in PL/SQL is a named block of code that performs a specific task and returns a
single value. Functions can take parameters, allowing you to pass in values for processing.
Unlike procedures, functions are designed to return a value, making them suitable for use in
SQL statements or other PL/SQL blocks.
1. Return Value: Functions must return a single value using the RETURN statement.
2. Parameters: Functions can accept parameters as IN (input) parameters. They do not
support OUT or IN OUT parameters.
3. Reusability: Functions can be called multiple times from various parts of the
application, enhancing code reuse.
4. Used in SQL: Functions can be used directly in SQL statements, making them
versatile for calculations and data manipulation.
Creating a Function
Syntax:
CREATE OR REPLACE FUNCTION function_name (parameter1 datatype, parameter2
datatype, ...)
RETURN return_datatype IS
BEGIN
-- PL/SQL block (statements) to perform the task
-- Return a value
RETURN return_value;
END function_name;
Components:
Example:
Executing a Function
To execute a function, you can use it in a PL/SQL block or in a SQL statement. In PL/SQL,
you call it just like you would call a procedure.
Syntax:
DECLARE
result datatype;
BEGIN
result := function_name(parameter_value);
DBMS_OUTPUT.PUT_LINE('Result: ' || result);
END;
/
Example:
DECLARE
v_result NUMBER;
BEGIN
v_result := calculate_square(5);
DBMS_OUTPUT.PUT_LINE('Square of 5: ' || v_result);
END;
/
To delete a function from the database, use the DROP FUNCTION statement.
Syntax:
DROP FUNCTION function_name;
Example:
Ans –
A database trigger is a special kind of stored procedure that automatically executes or fires
when certain events occur in the database. Triggers are associated with a specific table or
view and can respond to data manipulation events such as INSERT, UPDATE, or DELETE.
They can also respond to DML (Data Manipulation Language) events.
1. Data Validation: Triggers can enforce business rules and data integrity constraints
automatically, ensuring that data entered into the database meets specific criteria.
2. Audit Trail: They can be used to track changes to data, logging who made changes
and when they occurred. This is useful for auditing purposes.
3. Enforcing Referential Integrity: Triggers can maintain relationships between tables
by automatically enforcing rules when changes are made, such as preventing deletion
of records that are referenced in other tables.
4. Automatic Computation: Triggers can automatically compute values based on
changes to other fields or tables, allowing for real-time updates.
5. Synchronous Operations: Triggers can be used to perform synchronous operations
in the database, such as updating a summary table whenever a detailed table is
modified.
1. Row-Level Triggers: These triggers execute once for each row affected by the
triggering event (INSERT, UPDATE, DELETE).
2. Statement-Level Triggers: These triggers execute once for each SQL statement,
regardless of how many rows are affected.
3. Before Triggers: These are executed before the triggering event occurs. They are
useful for validating or modifying data before it is committed.
4. After Triggers: These are executed after the triggering event has occurred. They are
useful for actions that should take place after data changes, such as logging.
5. Instead of Triggers: These triggers are executed in place of the triggering event.
They are typically used for views to allow INSERT, UPDATE, or DELETE
operations that are normally not possible on views.
1. Creating a Trigger
Ans –
To create a database trigger, you use the CREATE TRIGGER statement. You can specify
whether the trigger should fire before or after a specific event, such as an INSERT,
UPDATE, or DELETE on a table.
Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF}
{INSERT | UPDATE | DELETE}
ON table_name
[FOR EACH ROW]
DECLARE
-- Optional: variable declarations
BEGIN
-- Trigger logic (PL/SQL statements)
END trigger_name;
Components:
Here’s an example of a trigger that logs any deletion of rows from an employees table into an
audit_log table.
CREATE OR REPLACE TRIGGER after_delete_employee
AFTER DELETE ON employees
FOR EACH ROW
BEGIN
INSERT INTO audit_log (employee_id, deleted_at)
VALUES (:OLD.employee_id, SYSDATE);
END after_delete_employee;
To delete a trigger from the database, you use the DROP TRIGGER statement.
Syntax:
DROP TRIGGER trigger_name;
Example: Deleting a Trigger
Ans –