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

03 PL SQL

The document provides an overview of PL/SQL including: - PL/SQL allows developers to write procedures, functions and triggers to extend capabilities of SQL in Oracle databases. - Key components of PL/SQL include blocks, procedures, cursors, triggers and error handling. - Procedures are named blocks that can take parameters and optionally return values. Cursors allow processing of multiple rows from a query one at a time. Triggers automatically execute in response to events like DML statements.

Uploaded by

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

03 PL SQL

The document provides an overview of PL/SQL including: - PL/SQL allows developers to write procedures, functions and triggers to extend capabilities of SQL in Oracle databases. - Key components of PL/SQL include blocks, procedures, cursors, triggers and error handling. - Procedures are named blocks that can take parameters and optionally return values. Cursors allow processing of multiple rows from a query one at a time. Triggers automatically execute in response to events like DML statements.

Uploaded by

DIVYA
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT 5

PL/SQL
CONTENTS
• PL/SQL QUICK REVIEW
• PROCEDURES
• CURSORS
• TRIGGERS
• ERROR HANDLING
• SECURITY LOCKS
Introduction to PL/SQL
• What is PL/SQL?

– Developed by Oracle corporation in the 1980s.

– It’s a procedure language extension for SQL and


Oracle relational database.
PL/SQL Block Basic syntax
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
PL/SQL Block description
• Declarations
– This section starts with the keyword DECLARE.
– It is an optional section and defines all variables, cursors, etc.

• Executable Commands
– It’s enclosed between keywords BEGIN and END.
– It’s a mandatory section.
– It consists of executable PL/SQL statements of the program.

• Exception Handling
– This section starts with the keyword EXCEPTION.
– This section is also an optional section.
– It contains exceptions that handle errors in the program.
Simple PL/SQL program
Print natural numbers from 1 to 5.

declare
i number;
begin
i:=1;
loop
dbms_output.put_line(i);
i:=i+1;
exit when i > 5;
end loop;
end;
Procedures
• It’s a named block of statement.
• It may or may not return a value.

SYNTAX:

CREATE [OR REPLACE] PROCEDURE procedure_name


[(parameter_name [IN | OUT | IN OUT] type [, …])]
{IS | AS}
BEGIN
<procedure body>
END procedure_name;
• A procedure has a header and a body. The
header consists of the name of the procedure
and the parameters or variables passed to the
procedure. The body consists or declaration
section, execution section and exception section
similar to a general PL/SQL Block.
Simple program using Procedure

create or replace procedure topperStudent


as
name students.s_name%type;
begin

select name from student where marks=(select max(marks) fr
om student)
dbms_output.put_line(name);
end;
Executing a Procedure

Procedure can be called in two ways −


• Using the EXECUTE keyword
• Calling the name of the procedure from a PL/SQL block

The above procedure can be called using


1) Execute topperStudent
2)Begin
topperStudent;
End;
Advantages and disadvantages
• Advantages of SP

The advantages of Stored Procedure (SP):


• It is faster
• It is Pre-compiled
• It reduce network traffic
• It is reusable
• It can handle complex operation
• It support nested SP
• It’s security is high.
• Disadvantages of SP

The disadvantage of Stored Procedure (SP):


• Need expert developer, Because it is so hard to
write code
• It’s debugging is hard
• It is not database independent. Its code may
vary based on database server.
Deleting a Procedure
• DROP PROCEDURE procedure-name;
• DROP PROCEDURE topperStudent;
Parameter Modes in PL/SQL
Subprograms
• In
• Out
• Inout
Example
This program finds the minimum of two values.
Here, the procedure takes two numbers using the
IN mode and returns their minimum using the
OUT parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
Cursor
• A cursor is a temporary area created in the main memory
when a SQL statement is executed. A cursor contains
information on a select statement and the rows of data
accessed by it.
• This temporary work area is used to store the data retrieved
from the database, and manipulate this data.
• A cursor can hold more than one row, but can process only
one row at a time. The set of rows the cursor holds is called
the active set.
• There are two types of cursors in PL/SQL:
– Implicit
– Explicit
Cursor Actions
• Declare Cursor: A cursor is declared by defining the SQL
statement that returns a result set.
• Open: A Cursor is opened and populated by executing the
SQL statement defined by the cursor.
• Fetch: When the cursor is opened, rows can be fetched
from the cursor one by one or in a block to perform data
manipulation.
• Close: After data manipulation, close the cursor explicitly.
• Deallocate: Finally, delete the cursor definition and release
all the system resources associated with the cursor.
syntax
CURSOR cursor_name
IS
SELECT_statement;
Example
CURSOR c1
IS
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;
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
• c_id customers.id%type;
• c_name customers.name%type;
• c_addr customers.address%type;
• CURSOR c_customers is
• SELECT id, name, address FROM customers;
• BEGIN
• OPEN c_customers;
• LOOP
• FETCH c_customers into c_id, c_name, c_addr;
• EXIT WHEN c_customers%notfound;
• dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
• END LOOP;
• CLOSE c_customers;
• END;
• /
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
• PL/SQL procedure successfully completed.
Implicit Cursor
• Implicit cursors get created when you execute
DML queries like Select, insert, delete, update.
• Oracle gives some useful attributes on this
implicit cursors to help us check the status of
DML operations
Attribute Usage

%FOUND If DML statement affects at least one row returns


TRUE else returns FALSE

%NOTFOUND If DML statement affects at least one row returns


FALSE else returns TRUE

%ROWCOUNT Return the number of rows affected by the DML


operations INSERT, DELETE, UPDATE, SELECT
Example of Implicit Cursor
create or replace procedure updateFees(newFee int)
as
var_rows number;
begin
update student set fees=newFee;
if SQL%FOUND then
var_rows :=SQL%ROWCOUNT;
dbms_output.put_line('The fees of '|| var_rows || ' students was
updated');
else
dbms_output.put_line('Some issue in updating');
end if;
end;
Explicit Cursor
• They must be created when you are executing a
SELECT statement that returns more than one
row in a PL/SQL procedure or a function.
• Even though the cursor stores multiple records,
only one record can be processed at a time,
which is called as current row. When you fetch a
row the current row position moves to next row.
• Both implicit and explicit cursors have the same
functionality, but they differ in the way they are
accessed.
Explicit Cursor : Example 1
• Show the average fees paid by students of each
department.

declare cursor c1
is
select deptName as Department,avg(fees) as Average_Fees from student
natural join department group by deptName;
rec1 c1%rowtype;
begin
for rec1 in c1 loop
dbms_output.put_line(rec1.Department ||' '||rec1.Average_Fees);
end loop;
end;
Bounded and unbounded cursors
• Bounded cursor bounds to a query
• cursor_name [ [NO] SCROLL ] CURSOR [( name
datatype, name data type, ...)]no FOR query;
• unbounded cursor variable is not bounded to
any query when it is declare it. So we have to
specify the query when we open it. See the
following example:
• OPEN my_cursor FOR SELECT * FROM city
WHERE counter = p_country;
Triggers
• Triggers are stored routines, which are
automatically executed when some events
occur.
• Triggers are written to be executed in response
to any of the following events:
• DML - DELETE, INSERT, or UPDATE.
• DDL - CREATE, ALTER, or DROP .
• A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Trigger: General Syntax
CREATE [ OR REPLACE ] TRIGGER trigger_name
BEFORE/AFTER INSERT/UPDATE/DELETE
ON table_name [ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION WHEN ...
-- exception handling
END;
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
 [OF col_name] − This specifies the column name that will be updated.
 [ON table_name] − This specifies the name of the table associated with the trigger.
 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
 WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
example

 CREATE OR REPLACE TRIGGER display_salary_changes


 BEFORE DELETE OR INSERT OR UPDATE ON customers
 FOR EACH ROW
 WHEN (NEW.ID > 0)
 DECLARE
 sal_diff number;
 BEGIN
 sal_diff := :NEW.salary - :OLD.salary;
 dbms_output.put_line('Old salary: ' || :OLD.salary);
 dbms_output.put_line('New salary: ' || :NEW.salary);
 dbms_output.put_line('Salary difference: ' || sal_diff);
 END;
 /
Exceptions
• An error condition during a program execution is
called an exception in PL/SQL.
• PL/SQL supports programmers to catch such
conditions using EXCEPTION block in the
program
•  There are two types of exceptions:
– System-defined exceptions
– User-defined exceptions
General Syntax
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements ........
WHEN others THEN
exception3-handling-statements
END;
System Defined Exception
DECLARE
dept department.deptNo%type:=10;
name department.deptName%type;
BEGIN
SELECT deptName into name FROM department where deptNo=dept;
DBMS_OUTPUT.PUT_LINE ('Name: '|| name);
EXCEPTION WHEN no_data_found THEN
dbms_output.put_line('No such department!');
WHEN others THEN
dbms_output.put_line('Error!');
END;

Here in this example, we have used system defined exception:


no_data_found
User defined exception
DECLARE
dept department.deptNo%type ;
name department.deptName%type;
ex_invalid_deptNo EXCEPTION;
BEGIN
IF dept <= 0 THEN
RAISE ex_invalid_deptNo;
ELSE
SELECT deptName into name
FROM department
WHERE deptNo = dept;
DBMS_OUTPUT.PUT_LINE (‘Department: '|| name);
END IF;
EXCEPTION
WHEN ex_invalid_deptNo THEN
dbms_output.put_line('Department number must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such department!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
Security locks
• Locks are mechanism used to ensure data
integrity.
• There are two types of Locks 
Shared lock
Exclusive lock
• Row Level locking
If the WHERE clause evaluates to only one
row in the table, a row level lock is used.
• Table Level locking
If there is no WHERE clause, the query
accesses the entire table, a table level lock is
used.
Can't update entire table data when update is
done by other user.
Syntax:
LOCK TABLE <tablename> [<tablename>]….. IN { ROW
SHARE / ROW EXCLUSIVE / SHARE UPDATE / SHARE /
SHARE ROW EXCLUSIVE / EXCLUSIVE}[NOWAIT]
• Deadlock
In a deadlock, two database operations wait for each
other to release a lock.
A deadlock occurs when two users have a lock, each
on a separate object, and, they want to acquire a lock on
each other's object.
When this happens, the first user has to wait for the
second user to release the lock, but the second user will
not release it until the lock on the first user's object is freed.
At this point, both the users are at a deadlock and
cannot proceed with their business.
Advisory locks
• PostgreSQL provides the means for creating
locks with application defined meaning. These
locks are called Advisory Locks 
• They are an ideal candidate for concurrency
control
• Advisory Locks can used to control access to a
shared resource in a distributed system.
Session and Transaction locks
• There are two ways to acquire advisory locks in
PostgreSQL, at session level or at transaction level.
Session level locks are held until the session ends
or until the lock is released manually.
• A lock acquired in a transaction will hold even if the
transaction rollbacks.
• A transactional advisory lock acquired in a
transaction will be released when the transaction
ends.

You might also like