0% found this document useful (0 votes)
14 views

Unit 4

Uploaded by

notpruthvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit 4

Uploaded by

notpruthvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT 4

Q) What is Pl/SQL. Advantages and Disadvantages of Pl/SQL?


Ans-
PL/SQL is a block structured language that enables developers to combine the power of SQL
with procedural statements.All the statements of a block are passed to oracle engine all at
once which increases processing speed and decreases the traffic.

Basics of PL/SQL

• •PL/SQL stands for Procedural Language extensions to the Structured Query


Language (SQL).
• PL/SQL is a combination of SQL along with the procedural features of
programming languages.
• Oracle uses a PL/SQL engine to processes the PL/SQL statements.
• PL/SQL includes procedural language elements like conditions and loops. It
allows declaration of constants and variables, procedures and functions, types and
variable of those types and triggers.

Advantages of Pl/SQL

1. Tight Integration with 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

• Developers can encapsulate business logic into stored procedures, functions,


packages, and triggers. This enhances maintainability by keeping the logic centralized
within the database layer.

6. Support for Modular Programming

• 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

• PL/SQL provides strong security measures by granting specific privileges to stored


procedures or functions, helping to restrict access to sensitive data.

8. Reduces Network Traffic

• 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.

9. Support for Triggers

• 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

• Vendor Lock-In: PL/SQL is proprietary to Oracle databases, meaning it is not easily


portable to non-Oracle environments. If you switch to a different database system,
you'll likely have to rewrite the code in another procedural language like T-SQL for
SQL Server.

2. Steep Learning Curve

• 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.

3. Performance Overheads for Complex Logic

• 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.

7. Error Handling Complexity

• 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.

8. Limited IDE Support

• PL/SQL doesn't have the same breadth of Integrated Development Environment


(IDE) support as some other languages. Though there are tools like Oracle SQL
Developer and TOAD, they may not be as feature-rich or intuitive as modern
development environments for other languages like Java, Python, or JavaScript.

9. Not Designed for Web or Mobile Applications

• PL/SQL is primarily a database-side technology and is not well-suited for building


web or mobile applications. You would typically need other frameworks or
technologies to handle the front-end, while PL/SQL serves the backend.

10. Dependency on Oracle-Specific Tools

• PL/SQL development often depends on Oracle-specific tools and frameworks, which


may incur additional costs for licensing and maintenance, and limit flexibility for
integrating with non-Oracle systems or open-source technologies.
Q) Difference between SQL and PL/SQL.

Ans –

SQL PL/SQL

PL/SQL is a block of codes that used


SQL is a single query that is used to
to write the entire program blocks/
perform DML and DDL operations.
procedure/ function, etc.

It is declarative, that defines what


PL/SQL is procedural that defines
needs to be done, rather than how
how the things needs to be done.
things need to be done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

It is an extension of SQL, so it can


Cannot contain PL/SQL code in it.
contain SQL inside it.

Q) Explain block structure of 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);

3. Exception Handling Section

• 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 –

Data Types in PL/SQL

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:

Common Data Types

• 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.

Advanced Data Types

• 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.

Syntax for Declaring a Variable:


variable_name data_type [DEFAULT initial_value];

here,

variable_name: The name of the variable.


data_type: The data type of the variable.
DEFAULT initial_value: (Optional) You can provide an initial value using the DEFAULT
keyword or by using the assignment operator :=.

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.

Syntax for Declaring a Constant:

constant_name CONSTANT data_type := value;

here,

constant_name: The name of the constant.


CONSTANT: Keyword used to define a constant.
data_type: The data type of the constant.
value: A fixed value that the constant holds.

Q) Explain all control structure in PL/SQL which contain Conditional


control, Iterative Control, Sequential Control.
Ans –

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

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.

There are several types of conditional control structures in PL/SQL:

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

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.

Types of Iterative Controls in PL/SQL

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;

-- Exit loop when counter reaches 5


EXIT WHEN counter > 5;
END LOOP;
END;

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);

result := num1 * num2; -- Perform multiplication


DBMS_OUTPUT.PUT_LINE('The product of num1 and num2 is: ' || result);

result := num2 - num1; -- Perform subtraction


DBMS_OUTPUT.PUT_LINE('The difference between num2 and num1 is: ' || result);
END;

Q) What is exception handling in pl/sql ? Explain predefined and user


defined exception.

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.

Components of Exception Handling

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:

Exception Name Description


NO_DATA_FOUND Raised when a SELECT INTO query returns no rows.
Raised when a SELECT INTO query returns more than
TOO_MANY_ROWS
one row.
ZERO_DIVIDE Raised when an attempt is made to divide a number by zero.
INVALID_CURSOR Raised when an illegal operation is performed on a cursor.
Raised when an arithmetic, conversion, or truncation error
VALUE_ERROR
occurs.
Raised when an attempt is made to open an already open
CURSOR_ALREADY_OPEN
cursor.

Syntax of Predefined Exception Handling:

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;

Example of Predefined Exception:

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.

Steps to Handle User-Defined Exceptions:

1. Declare the exception in the DECLARE section.


2. Raise the exception using the RAISE statement.
3. Handle the exception in the EXCEPTION section.

Syntax for User-Defined Exception:

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;

Example of User-Defined Exception:

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;

Q) What is a difference between user-defined and pre-defined exception in


pl/sql?

Ans –

Q) What is cursor? Explain explicit cursor and implicit cursor.

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:

PL/SQL supports two 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 −

S.No Attribute & Description

%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.

The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −

• Declaring the cursor for initializing the memory


• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory
Declaring the Cursor

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

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 −

FETCH c_customers INTO c_id, c_name, c_addr;


Closing the Cursor

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;

-- Variables to hold the data fetched from the cursor


v_emp_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Open the cursor
OPEN emp_cursor;

-- Fetch rows one by one using a loop


LOOP
FETCH emp_cursor INTO v_emp_id, v_first_name, v_salary;

-- Exit the loop when no more rows are fetched


EXIT WHEN emp_cursor%NOTFOUND;

-- Process the fetched data


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ', Name: ' || v_first_name || ',
Salary: ' || v_salary);
END LOOP;

-- Close the cursor


CLOSE emp_cursor;
END;
Q) Explain the following terms

a) Opening and closing of cursor

b) declaring of cursor

c) fetching a record from cursor

f) cursor for loop

e) parameterized cursor

Ans –

a) Opening and closing of cursor

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:

Opening an Explicit Cursor

When you open a cursor, the following steps occur:

1. The SELECT statement associated with the cursor is executed.


2. The result set (rows that match the query) is identified and made available for
fetching.
3. Memory is allocated to store the context of the cursor, including its result set.

Syntax for Opening a Cursor:


OPEN cursor_name;

Once a cursor is opened, it remains open until explicitly closed, and you can begin fetching
rows from it.

Example of Opening a Cursor:


DECLARE
CURSOR emp_cursor IS
SELECT employee_id, first_name FROM employees WHERE department_id = 10;
BEGIN
-- Open the cursor
OPEN emp_cursor;
END;
Closing an Explicit Cursor

Once you have finished fetching rows from the cursor, or when the cursor is no longer
needed, it should be closed to:

1. Release the memory and resources allocated for the cursor.


2. Mark the cursor as no longer available for fetching data.
3. Ensure that the cursor can be reopened later if needed (in case it’s declared within a
loop or procedure).

Syntax for Closing a Cursor:


CLOSE cursor_name;

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.

Example of Closing a Cursor:


DECLARE
CURSOR emp_cursor IS
SELECT employee_id, first_name FROM employees WHERE department_id = 10;
BEGIN
-- Open the cursor
OPEN emp_cursor;

-- (Fetch operations would go here)

-- Close the cursor


CLOSE emp_cursor;
END;

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.

Syntax for Cursor Declaration:

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;

c) fetching a record from cursor

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.

Syntax for Fetching Records:

FETCH cursor_name INTO variable1, variable2, ...;

• 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.

Attributes for Cursor Fetching:

• cursor_name%FOUND: Returns TRUE if a row was successfully fetched.


• cursor_name%NOTFOUND: Returns TRUE if no more rows are available.
• cursor_name%ROWCOUNT: Returns the number of rows fetched so far.

Example of Fetching a Single Record:

DECLARE
CURSOR emp_cursor IS
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id = 10;

-- Variables to hold the fetched values


v_emp_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Open the cursor
OPEN emp_cursor;

-- Fetch the first row into the variables


FETCH emp_cursor INTO v_emp_id, v_first_name, v_salary;

-- Display the fetched data


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ', Name: ' || v_first_name || ',
Salary: ' || v_salary);

-- Close the cursor


CLOSE emp_cursor;
END;

f) cursor for loop

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.

Syntax of Cursor FOR Loop:

FOR record_name IN cursor_name LOOP


-- Access the fields of the record using dot notation
-- Process each row inside the loop
END LOOP;

• 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.

Example of a Cursor FOR Loop:

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.

Syntax for Parameterized Cursor:

CURSOR cursor_name (parameter_name datatype, ...) IS


SELECT_statement;

• cursor_name: Name of the cursor.


• parameter_name: The name of the parameter that the cursor will accept.
• datatype: The data type of the parameter, similar to variable declarations in PL/SQL.
• SELECT_statement: The SQL query that can use the passed parameters in its
conditions (WHERE, JOIN, etc.).

Example of a Parameterized Cursor:

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;

-- Variables to hold the fetched values


v_emp_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Open the cursor with a specific department ID (e.g., 20)
OPEN emp_cursor(20);

-- Fetch the first row


FETCH emp_cursor INTO v_emp_id, v_first_name, v_salary;

-- Display the fetched data


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ', Name: ' || v_first_name || ',
Salary: ' || v_salary);

-- Close the cursor


CLOSE emp_cursor;
END;

Q) What is mean by procedure in pl/sql? Enlist the advantages of


procedure with explanation.

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.

Key Characteristics of Procedures:

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.

Basic Structure of a Procedure:

CREATE OR REPLACE PROCEDURE procedure_name


(parameter1 datatype, parameter2 datatype, ...) IS
BEGIN
-- Body of the procedure
-- PL/SQL statements to perform actions
END procedure_name;

• Procedure Name: The identifier for the procedure.


• Parameters: Optional input or output parameters that the procedure accepts or
returns.
• PL/SQL Statements: The block of code inside the BEGIN and END that defines the
actions to be performed.

Example of a Simple Procedure:

CREATE OR REPLACE PROCEDURE greet_user (p_name IN VARCHAR2) IS


BEGIN
DBMS_OUTPUT.PUT_LINE('Hello, ' || p_name || '!');
END greet_user;
Advantages of Using Procedures:

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.

Q) How to create, execute and delete stored procedure in pl/sql.

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.

1. Creating a Stored Procedure

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:

• procedure_name: The name of the procedure.


• Parameters: You can define parameters as IN, OUT, or IN OUT.
o IN: Accepts a value passed to the procedure.
o OUT: Returns a value from the procedure.
o IN OUT: Passes a value in and returns a modified value out.
• Procedure Body: Contains the actions or logic that the procedure performs, written in
PL/SQL between BEGIN and END.

Example:

A stored procedure that takes an employee's ID and prints their salary.

CREATE OR REPLACE PROCEDURE get_salary (p_emp_id IN NUMBER) IS


v_salary NUMBER;
BEGIN
SELECT salary INTO v_salary FROM employees WHERE employee_id = p_emp_id;
DBMS_OUTPUT.PUT_LINE('Employee Salary: ' || v_salary);
END get_salary;

• 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.

2. Executing a Stored Procedure

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:

• procedure_name: The name of the procedure you want to execute.


• parameters: The actual values passed to the parameters defined in the procedure.

Example:

Execute the get_salary procedure for an employee with ID 101.

BEGIN
get_salary(101);
END;
/

This will output the salary of the employee with ID 101 to the console using
DBMS_OUTPUT.PUT_LINE.

3. Deleting (Dropping) a Stored Procedure

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:

• procedure_name: The name of the procedure you want to delete.


Example:

Delete the get_salary procedure from the database.

DROP PROCEDURE get_salary;

This will remove the get_salary procedure from the schema.

Q) What is functions in pl/sql? How to create, Execute and delete function


in pl/sql.

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.

Key Features of Functions:

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

To create a function, you use the CREATE OR REPLACE FUNCTION statement.

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:

• function_name: The name of the function.


• Parameters: Define input parameters for the function.
• RETURN return_datatype: Specifies the data type of the value the function will
return.
• Procedure Body: Contains the logic to perform the task, including the RETURN
statement to send back a value.

Example:

A function to calculate the square of a number.

CREATE OR REPLACE FUNCTION calculate_square (p_number IN NUMBER)


RETURN NUMBER IS
BEGIN
RETURN p_number * p_number;
END calculate_square;

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:

Execute the calculate_square function to find the square of 5.

DECLARE
v_result NUMBER;
BEGIN
v_result := calculate_square(5);
DBMS_OUTPUT.PUT_LINE('Square of 5: ' || v_result);
END;
/

Deleting (Dropping) a Function

To delete a function from the database, use the DROP FUNCTION statement.

Syntax:
DROP FUNCTION function_name;
Example:

Delete the calculate_square function from the database.

DROP FUNCTION calculate_square;


Q) What is mean by database triggers? Explain uses of database triggers
and types of database triggers.

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.

Uses of Database Triggers

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.

Types of Database Triggers

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.

Syntax of Database Triggers

1. Creating a Trigger

CREATE [OR REPLACE] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF}
{INSERT | UPDATE | DELETE}
ON table_name
[FOR EACH ROW]
DECLARE
-- Variable declarations
BEGIN
-- Trigger logic
END trigger_name;

• trigger_name: The name of the trigger.


• BEFORE or AFTER: Specifies when the trigger should fire.
• INSERT, UPDATE, DELETE: The event that activates the trigger.
• table_name: The name of the table on which the trigger is defined.
• FOR EACH ROW: Optional; specifies that the trigger will fire once for each row
affected.

Q) How to create and delete database trigger.

Ans –

Creating a Database Trigger

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:

• trigger_name: The name you assign to the trigger.


• BEFORE or AFTER: Indicates when the trigger should fire.
• INSERT, UPDATE, DELETE: The specific event that activates the trigger.
• table_name: The name of the table on which the trigger is defined.
• FOR EACH ROW: Optional; indicates the trigger will execute once for each row
affected by the event.
• DECLARE: Optional section for declaring variables.
• BEGIN ... END: Contains the logic that defines what the trigger does.

Example: Creating a Trigger

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;

Deleting a Database Trigger

To delete a trigger from the database, you use the DROP TRIGGER statement.

Syntax:
DROP TRIGGER trigger_name;
Example: Deleting a Trigger

To remove the previously created after_delete_employee trigger, you would execute:

DROP TRIGGER after_delete_employee;


Q) What is a difference between procedure, function and trigger in pl/sql.

Ans –

You might also like