Unit 4 (2)
Unit 4 (2)
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 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.
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.
MONTH
DAY
HOUR
MINUTE
SECOND
PL/SQL Variables
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.
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;
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;
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.
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.
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:
OUTPUT:
1 to 10
Sequential Control
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;
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.
DECLARE
my-exception EXCEPTION;
There are many pre-defined exception in PL/SQL which are executed when any
database rule is violated by the programs.
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.
Implicit cursors
Explicit cursors
1. Implicit Cursors:
%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.
%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;
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:
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.
5. **END LOOP**: When we've gone through all the rows in the "employees"
table, the loop ends.
END procedure_name;
Description:
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure
Executing procedures:
Deleting Procedure:
A procedure is deleted with the DROP PROCEDURE statement.
Advantages:
Description:
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.
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.
```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;
/
```
4. **Logging**: Capturing events and actions for later analysis and debugging.
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:
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.
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.