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

Unit 4 (2)

Uploaded by

vrusha017
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit 4 (2)

Uploaded by

vrusha017
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit 4

PlSQL:Pl/SQL stands for "Procedural Language extension of SQL" that is used in


Oracle. PL/SQL is a block structured language. The programs of PL/SQL are
logical blocks that can contain any number of nested sub-blocks. PLSQL allows
the programmer to write code in procedural format.

PL/SQL is a procedural language designed specifically to embrace SQL statements


within its syntax. PL/SQL program units are compiled by the Oracle Database
server and stored inside the database. And at run-time, both PL/SQL and SQL run
within the same server process.

Advantages of PLSQL

1. High-Level of Execution
Unlike SQL, where a single statement executes one at a time, PL/SQL executes the
entire block of code containing multiple statements.
2. Increased Performance
It executes the entire block of code in one go instead of sending the statements to
the database one by one.
3. Compatibility with SQL
PL/SQL aims to combine procedural programming language and database
language. It extends the capabilities of SQL by adding procedural features like
loops, conditions, and data handling.
4. Better Productivity
PL/SQL allows you to write compact programs in the form of blocks of code,
leading to increased execution.
5. Error Management
PL/SQL performs exception handling (runtime errors) efficiently. It has a wide
range of means to assist you in identifying errors, diagnosing them, and informing
users of application-specific issues.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped.
Below are different sections of PL/SQL blocks.

1. Declaration section
2. Execution section
3. Exception-Handling section
The below picture illustrates the different PL/SQL block and their section order.
The Declaration section: Code block start with a declaration section, in which
memory variables, constants, cursors and other oracle objects can be declared and
if required initialized.

The Begin section: Consist of set of SQL and PL/SQL statements, which
describe processes that have to be applied to table data. Actual data manipulation,
retrieval, looping and branching constructs are specified in this section.

The Exception section: This section deals with handling errors that arise during
execution data manipulation statements, which make up PL/SQL code block.
Errors can arise due to syntax, logic and/or validation rule.

The End section: This marks the end of a PL/SQL block.


Broadly, PL/SQL blocks are two types: Anonymous blocks and Named blocks
are as follows:
1. Anonymous blocks: In PL/SQL, Those blocks which doesn’t have header are
known as anonymous blocks.
2. Named blocks: In PL/SQL those blocks which are having header or labels are
known as Named blocks.

PL/SQL Execution Environment:

 The PL/SQL engine resides in the Oracle engine.The Oracle engine can
process not only single SQL statement but also block of many statements.
 The call to Oracle engine needs to be made only once to execute any
number of SQL statements if these SQL statements are bundled inside a
PL/SQL block.

PLSQL data types

S.N
Data Type & Description
o

Numeric
1
Numeric values on which arithmetic operations are performed.

Character
2 Alphanumeric values that represent single characters or strings of
characters.

Boolean
3
Logical values on which logical operations are performed.

Datetime
4
Dates and times.
1. PL/SQL Numeric Data Types
 FLOAT
 INT
2. PL/SQL Character Data Types
 CHAR
 VARCHAR2
3. PL/SQL Boolean Data Types
 The BOOLEAN data type stores logical values that are used in logical
operations. The logical values are the Boolean
values TRUE and FALSE and the value NULL.

4. PL/SQL Datetime and Interval Types


YEAR

MONTH

DAY

HOUR

MINUTE

SECOND

PL/SQL Variables

 A variable is a meaningful name which facilitates a


programmer to store data temporarily during the
execution of code.

 It is nothing except a name given to a storage area.

 Each variable in the PL/SQL has a specific data type


which defines the size and layout of the variable's
memory.

 PL/SQL variables must be declared in the declaration


section or in a package.
Syntax for declaring a variable is −

variable_name datatype [NOT NULL := value]

Example: a integer :=10;

Initializing Variables in PL/SQL

Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If


you want to initialize a variable with a value other than the NULL value, you can
do so during the declaration.

Variable Scope in PL/SQL

PL/SQL allows the nesting of blocks, i.e., each program block may contain another
inner block. If a variable is declared within an inner block, it is not accessible to
the outer block. However, if a variable is declared and accessible to an outer block,
it is also accessible to all nested inner blocks.

 Local variables − Variables declared in an inner block and not accessible to


outer blocks.
 Global variables − Variables declared in the outermost block or a package.

Constants; In this chapter, we will discuss constants and literals in PL/SQL. A


constant holds a value that once declared, does not change in the program. A
constant declaration specifies its name, data type, and value, and allocates storage
for it

Example: PI CONSTANT NUMBER :=3.141592654;


Control Statements:

 The IF statement executes a sequence of statements depending on the value


of a condition.
 There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-
THEN-ELSIF.
 Syntax: (IF-THEN statement):
 IF condition
 THEN
 Statement: {It is executed when condition is true}
 END IF;
 This syntax is used when you want to execute statements only when
condition is TRUE.

Example:
DECLARE
a number(3) := 100;
BEGIN
IF( a < 20 ) THEN
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;

Output: a is not less than 20


value of a is : 500
PL/SQL procedure successfully completed.

 Syntax: (IF-THEN-ELSE statement):

 IF condition
 THEN
 {...statements to execute when condition is TRUE...}
 ELSE
 {...statements to execute when condition is FALSE...}
 END IF;
 This syntax is used when you want to execute one set of statements when
condition is TRUE or a different set of statements when condition is
FALSE.
 Example:
DECLARE
a number(3) := 100;
BEGIN
IF( a < 20 ) THEN
 dbms_output.put_line('a is less than 20 ' );
ELSE
 dbms_output.put_line('a is not less than 20 ' );
 END IF;
 dbms_output.put_line('value of a is : ' || a);
 END;

 Syntax: (IF-THEN-ELSIF statement):


 IF condition1
 THEN
 {...statements to execute when condition1 is TRUE...}
 ELSIF condition2
 THEN
 {...statements to execute when condition2 is TRUE...}
 END IF;
 This syntax is used when you want to execute one set of statements when
condition1 is TRUE or a different set of statements when condition2 is
TRUE.

Iterative Control

The PL/SQL loops are used to repeat the execution of one or more
statements for specified number of times. These are also known as iterative
control statements.

Types of PL/SQL Loops

There are 3 types of PL/SQL Loops.

1. Basic Loop / Exit Loop


2. While Loop
3. For Loop
Basic Loop: EXIT condition is specified in the loop, otherwise the loop will
get into an infinite number of iterations.

 Syntax for a basic loop:


LOOP
Sequence of statements;
END LOOP;
 Example:
DECLARE
I INTEGER := 1;
BEGIN
WHILE i <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
Exit;
END LOOP;
END;
Output: 1

1. While Loop: PL/SQL while loop is used when a set of statements has to be
executed as long as a condition is true, the While loop is used. The condition
is decided at the beginning of each iteration and continues until the condition
becomes false.

 Syntax of while loop:


WHILE <condition>
statements;
END LOOP;
 Example:
DECLARE
I INTEGER := 1;
BEGIN
WHILE i <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
Output:
1
2
3
4
5
6
7
8
9
10

2. FOR LOOP: PL/SQL for loop is used when you want to execute a set of
statements for a predetermined number of times. The loop is iterated
between the start and end integer values. The counter is always incremented
by 1 and once the counter reaches the value of end integer, the loop ends.
 Syntax of for loop:

FOR counter IN initial_value .. final_value LOOP


statements;
END LOOP;
 Example:
BEGIN
FOR k IN 1..10 LOOP
-- note that k was not declared
DBMS_OUTPUT.PUT_LINE(k);
END LOOP;
END;

OUTPUT:
1 to 10

 Sequential Control

Loop control statements: PL/SQL supports the following control statements.


Labeling loops also help in taking the control outside a loop.
1. Continue Statements: The CONTINUE statement causes the loop to skip
the remainder of its body and immediately retest its condition prior to
reiterating. In other words, it forces the next iteration of the loop to take
place, skipping any code in between.

Syntax: CONTINUE;
Example:
DECLARE
a number(2):=10;
BEGIN
--while loop execution
WHILE a <20 LOOP
dbms_output.put_line ('value of a: '|| a);
a := a +1;
IF a =15 THEN
-- skip the loop using the CONTINUE statement
a := a +1;
CONTINUE;
END IF;
END LOOP;
END;
Output:
10
11
12
131
14
16
17
18
19
20
2. GOTO Statement: A GOTO statement in PL/SQL programming language
provides an unconditional jump from the GOTO to a labeled statement in the
same subprogram.
NOTE − The use of GOTO statement is not recommended in any programming
language because it makes it difficult to trace the control flow of a program,
 Syntax: GOTO label;
..
<< label >>
statement;

 Exception: An error occurs during the program execution is called


Exception in PL/SQL.
PL/SQL provides us the exception block which raises the exception thus
helping the programmer to find out the fault and resolve it.
There are two types of exceptions defined in PL/SQL
1. 1. User defined exception.
2. 2. System defined exceptions.
 Syntax:
BEGIN
EXCEPTION

WHEN exception1 THEN


exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
Exception N-handling-statements
END;
 PL/SQL User-defined Exceptions

PL/SQL facilitates their users to define their own exceptions according to the need
of the program. A user-defined exception can be raised explicitly, using either a
RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.

 Syntax for user define exceptions

DECLARE
my-exception EXCEPTION;

 PL/SQL Pre-defined Exceptions

There are many pre-defined exception in PL/SQL which are executed when any
database rule is violated by the programs.

Ex: For example, the predefined exception NO_DATA_FOUND is raised when


a SELECT INTO statement returns no rows.

 Cursors
 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;
 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 known as active set.

There are two types of cursors −

 Implicit cursors
 Explicit cursors

1. Implicit Cursors:

 Implicit (InDirectly)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.
 If we want to know how many num of records we have deleted, inserted or
how many rows we have selected from select statements this all information
if we want to know in runtime then we have some attributes
 S.No Attribute & Description

%FOUND
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.
1 (If we haven’t opened cursor then it return invalid cursor as its
dependant on ISOPEN)(if it is open it checks for number of
rows and if there are 10 rows it goes 1 by 1 and finds every row
at first it will check 1st row it returns true, for 2nd row it returns
true till 10 it returns true unless and until the value is found it
returns true and at 11th row it will return false)

%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an
INSERT, UPDATE, or DELETE statement affected no rows, or
a SELECT INTO statement returned no rows. Otherwise, it
2 returns FALSE.

(opposite of found, such as if there are 10 rows and it goes 1 by


1 at row value is found it returns false , 2nd false till 10 and once
when there is no value found it returns true)

%ISOPEN
Always returns FALSE for implicit cursors, because Oracle
3 closes the SQL cursor automatically after executing its
associated SQL statement.(it returns the Boolean value true or
false)(if cursor is open then it returns true value and if cursor is
not opened then it returns false value)

4 %ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE,
or DELETE statement, or returned by a SELECT INTO
statement.
(if we want to know currently on which row the cursor is
working or how many num of rows are affected we can use
rowcount it returns number of records)
Any SQL cursor attribute will be accessed as sql%attribute_name ex: sql
%rowcount
(If we want to use this cursor we have to start with sql% because it is not under
programmers control)

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.
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 Ex: OPEN c_customers;

Fetching the cursor for retrieving the data Ex: FETCH c_customers

 Closing the cursor to release the allocated memory

Cursor For loop: Cursor FOR loop is used to simplify the fetching and processing
of data.
 A cursor FOR loop automatically handles cursor declaration, opening,
fetching, and closing, making your code more concise.
 Think of a cursor like a pointer or a way to access rows in a database.
 Here's how you can use a cursor FOR loop in PL/SQL:

```sql
BEGIN
-- Declare a cursor for loop
FOR emp_rec IN (SELECT employee_id, first_name FROM employees)
LOOP
-- Access individual fields from the cursor record
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_rec.employee_id || ',
Name: ' || emp_rec.first_name);
END LOOP;
END;
/
```
Output: Employee ID:1,Name:JohnSmith

Employee ID:2,Name:JaneDoe

Employee ID:3,Name:RobertJohnson

Description:

1. **Declare a Cursor**: In this code, we're creating a cursor called `emp_rec` to


go through the rows of a table called "employees."

2. **FOR Loop**: Now, we're using a loop (similar to a repetitive action) to go


through each row in the "employees" table one by one.

3. **Accessing Data**: Inside the loop, we are picking out specific pieces of
information from each row. Specifically, we're getting the "employee_id" and
"first_name" for each employee.

4. **Printing Information**: We're then printing this information to the screen


using `DBMS_OUTPUT.PUT_LINE`. It's like printing a message on your
computer screen.

5. **END LOOP**: When we've gone through all the rows in the "employees"
table, the loop ends.

Parameterized Cursor: A parameterized cursor allows you to pass values as


parameters into the cursor is known as parameterized cursor.
Example: OPEN employee_cursor(department_id,salary);

Procedures: A procedure is created with the CREATE OR REPLACE


PROCEDURE statement.

Syntax: CREATE [OR REPLACE] PROCEDURE procedure_name As


BEGIN
< procedure_body >

END procedure_name;

Description:
 procedure-name specifies the name of the procedure.
 [OR REPLACE] option allows the modification of an existing procedure

Example:CREATE OR REPLACE PROCEDURE greetings


AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/

Executing procedures:

 Using the EXECUTE keyword


 Calling the name of the procedure from a PL/SQL block

Example: EXECUTE greetings;

Output: Hello World

Deleting Procedure:
A procedure is deleted with the DROP PROCEDURE statement.

Syntax: DROP PROCEDURE procedure-name;

Example: : DROP PROCEDURE greetings;

Advantages:

Functions: A function is created using the CREATE FUNCTION statement.


Syntax: CREATE [OR REPLACE] FUNCTION function_name
RETURN return_datatype
BEGIN
< function_body >
END [function_name];
 Description:
 function-name specifies the name of the function.
 [OR REPLACE] option allows the modification of an existing function.
 The function must contain a return statement.
 The RETURN clause specifies the data type

create or replace function adder(n1 in number, n2 in number)


return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
/
Output: Function created.

Description:

1. **Function Name**: The function is named `adder`.

2. **Input Parameters**: It accepts two input parameters, `n1` and `n2`, both of
which should be numbers (specifically, of the `NUMBER` data type).

3. **Return Type**: The function returns a single number as its result, which is
specified by the `RETURN NUMBER` declaration.
4. **Function Body**: Inside the function, it performs a simple addition operation
by adding `n1` and `n2` and stores the result in a variable `n3`.

5. **Return Statement**: The function then returns the value of `n3` as the result
of the function.

Execution:
Example:
DECLARE
n3 number(2);
BEGIN
n3 := adder(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
/
1. **DECLARE**: It declares a variable `n3` to hold a number with up to 2 digits.

2. **BEGIN**: This is the start of the code block where the main operations
happen.

3. **n3 := adder(11, 22)**: It calls the `adder` function, passing 11 and 22 as


input. The function calculates the sum of these numbers and returns it, which is
then stored in the variable `n3`.

4. **dbms_output.put_line('Addition is: ' || n3)**: It displays a message on the


screen using the `DBMS_OUTPUT.PUT_LINE` procedure. The message says
"Addition is:" followed by the value of `n3`.

So, when you run this code, it will call the `adder` function to add 11 and 22, and
then it will print the result, which is "Addition is: 33" because 11 + 22 is 33.

Delete Function: Drop Function is used to remove your created function from the
database.
Syntax: DROP FUNCTION function_name;
Example: DROP FUNCTION addr;
Triggers:
In PL/SQL, database triggers are stored procedures that are executed automatically
in response to specific events or conditions that occur within a database. These
triggers are associated with database tables, views, or schemas and can be used to
enforce data integrity, implement business logic, or perform specific actions when
certain events take place. There are two main types of database triggers:

1. **Row-Level Triggers:**
- Row-level triggers are executed once for each row affected by the triggering
event (e.g., an INSERT, UPDATE, or DELETE operation).
- They can be used to enforce constraints on individual rows, audit changes, or
implement fine-grained data validation.
- Common row-level triggers include BEFORE INSERT, BEFORE UPDATE,
BEFORE DELETE, AFTER INSERT, AFTER UPDATE, and AFTER DELETE
triggers.

2. **Statement-Level Triggers:**
- Statement-level triggers are executed once for each SQL statement that triggers
the event, regardless of the number of rows affected.
- They are used for tasks that involve multiple rows or for auditing database-wide
changes.
- Common statement-level triggers include BEFORE INSERT, BEFORE
UPDATE, and BEFORE DELETE triggers.

Here is an example of a simple PL/SQL trigger:

```sql
CREATE OR REPLACE TRIGGER example_trigger
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 0 THEN
raise_application_error(-20001, 'Salary cannot be negative');
END IF;
END;
/
```

In this example, we create a row-level trigger named `example_trigger` that is


executed before an `INSERT` operation on the `employees` table. It checks if the
salary being inserted is negative and raises an error if it is.

Common uses of database triggers in PL/SQL include:

1. **Data Validation**: Ensuring data consistency and integrity by implementing


checks and constraints.

2. **Auditing**: Recording changes to database records for security and auditing


purposes.

3. **Automatic Data Updates**: Automatically updating related data when


changes occur in specific tables.

4. **Logging**: Capturing events and actions for later analysis and debugging.

5. **Enforcing Business Rules**: Implementing business logic or workflow rules


within the database.

It's important to use triggers judiciously and consider their impact on performance,
as poorly designed triggers can lead to unexpected behavior or slow database
operations. Properly designed triggers can be a valuable tool for managing data and
enforcing business rules within your database.
Use of Triggers:
Triggers in a database are used to automate and enforce various actions,
validations, and business rules in response to specific events or changes in data.
Here are some common use cases and benefits of using triggers:

1. **Data Validation and Integrity**: Triggers can enforce data integrity by


validating incoming data to ensure that it adheres to specific rules or constraints.
For example, you can use triggers to check that certain fields are not null or that
data falls within permissible ranges.

2. **Auditing and Logging**: Triggers can automatically log changes made to


data, providing an audit trail for security and compliance purposes. This can help
track who made changes, when, and what changes were made.

3. **Automatic Data Updates**: Triggers can maintain data consistency by


automatically updating related data when changes occur. For example, when a
sales order is updated, a trigger can recalculate totals or update inventory levels.

4. **Enforcing Business Rules**: Business rules and workflow logic can be


enforced using triggers. For instance, you can use a trigger to ensure that certain
conditions are met before allowing a transaction to proceed.

5. **Complex Calculations**: Triggers can perform complex calculations and


derivations based on incoming data. For instance, a trigger can calculate a user's
account balance or score based on various inputs.

6. **Security and Access Control**: Triggers can help enforce access control and
security measures. They can prevent unauthorized users from performing specific
actions, such as updating sensitive records.

7. **Notification and Alerts**: Triggers can generate notifications and alerts based
on specific events. For example, when a critical change occurs, a trigger can send
an email or a message to relevant parties.
8. **Denormalization**: In data warehousing and reporting, triggers can be used
to denormalize data, creating aggregated views that enhance query performance for
complex analytical queries.

9. **Cascading Actions**: Triggers can trigger cascading actions, ensuring that


changes in one table propagate to other related tables, maintaining data
consistency.

10. **Default Values**: Triggers can automatically populate default values in


columns when records are inserted.

11. **Complex Data Transformation**: In some cases, triggers can transform


incoming data from one format to another, making it compatible with the database
schema.

12. **Historical Data Capture**: Triggers can capture and archive historical data
for later analysis and reporting.

It's important to use triggers judiciously and with caution, as they can introduce
complexity into a database and impact performance. Poorly designed or misused
triggers can lead to unexpected consequences and performance issues. Therefore,
when implementing triggers, it's essential to thoroughly plan, test, and document
their behavior to ensure they serve their intended purpose effectively and
efficiently.

You might also like