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

Ch13 PL SQL

Uploaded by

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

Ch13 PL SQL

Uploaded by

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

PL/SQL Concepts

Topics to be covered
• PL/SQL Basics
• Stored Procedures
• Cursors
• Database Triggers

PL/SQL Concepts 2
PL/SQL: Procedural Language/Structured Query Language

PL/SQL Concepts 3
PL/SQL
 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, bringing optimal efficiency.
 PL/SQL automatically inherits the robustness, security, and
portability of the Oracle Database.

PL/SQL Concepts 4
Advantages of PL/SQL

PL/SQL Concepts 5
Advantages of PL/SQL
 Block structure:
• PL/SQL consist of block of code, which can be nested within each other.
• Each block forms a unit of a task or a logical module.
• PL/SQL blocks can be stored in the database and reused.
 Procedural language capability:
• PL/SQL consist of procedural constructs such as conditional statements (if, if else,
nested if, else if ladder) and loops (for, while, do while).
 Better performance:
• PL/SQL engine processes multiple SQL statements simultaneously as a single block,
thereby reducing network traffic.
 Error handling:
• PL/SQL handles errors or exceptions effectively during the execution of PL/SQL
program.
• Once an exception is caught, specific action can be taken depending upon the type
of the exception or it can be displayed to the user with message.
PL/SQL Concepts 6
Features of PL/SQL

PL/SQL Concepts 7
Architecture of PL/SQL

PL/SQL Concepts 8
Arithmetic operators

PL/SQL Concepts 9
Expression operators

PL/SQL Concepts 10
Comments

PL/SQL Concepts 11
Declaration of Variables & Value Assignment

PL/SQL Concepts 12
Declaration of Variables & Value Assignment
With Select into statement Select col_name into
var_name where cond;
Examples:

PL/SQL Concepts 13
Program
 Wap to calculate total sal of emp having empno 100.
 Table emp1 having empno, ename, bp, da, hra, total columns.

PL/SQL Concepts 14
Constant Declaration

PL/SQL Concepts 15
Variable Attributes
 Attributes allow us to refer to data types and objects from the
database.
 PL/SQL variables and constants can have attributes.
 The following are the types of attributes, which are supported by
PL/SQL.
 %TYPE: Use of this attribute ensures that type compatibility
between table columns and PL/SQL variables is maintained. The
%TYPE attribute can also be used with formal parameter
declarations.
 %ROWTYPE : The %ROWTYPE attribute is used to define a record
with fields corresponding to all of the columns that are fetched
from a cursor or cursor variable.

PL/SQL Concepts 16
Variable Attributes

PL/SQL Concepts 17
Displaying user messages

PL/SQL Concepts 18
Control structures of PL/SQL

PL/SQL Concepts 19
Conditional Control

PL/SQL Concepts 20
Illustration of IF-THEN-ELSIF, PL/SQL block to calculate addition, subtraction,
multiplication and division of two numbers according to user choice.

PL/SQL Concepts 21
Iterative Control

PL/SQL Concepts 22
Iterative Control
Example of PL/SQL EXIT Loop
DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;

PL/SQL Concepts 23
Iterative Control

PL/SQL Concepts 24
Iterative Control

PL/SQL Concepts 25
 Illustration of WHILE LOOP, PL/SQL block to print multiplication table of
any number

PL/SQL Concepts 26
Iterative Control

PL/SQL Concepts 27
Iterative Control

PL/SQL Concepts 28
Iterative Control
PL/SQL For Loop Example 2
DECLARE
VAR1 NUMBER;
BEGIN
VAR1:=10;
FOR VAR2 IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
END LOOP;
END;

PL/SQL Concepts 29
Iterative Control

PL/SQL Concepts 30
PL/SQL Case Statement
Syntax for the CASE Statement:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
Example of PL/SQL case statement
END 1.DECLARE
2. grade char(1) := 'A';
3.BEGIN
4. CASE grade
5. when 'A' then dbms_output.put_line('Excellent');
6. when 'B' then dbms_output.put_line('Very good');
7. when 'C' then dbms_output.put_line('Good');
8. when 'D' then dbms_output.put_line('Average');
9. when 'F' then dbms_output.put_line('Passed with Grace
');
10. else dbms_output.put_line('Failed');
11. END CASE;
12.END;
Excellent PL/SQL procedure successfully completed.

PL/SQL Concepts 31
Sub Programs Functions & Procedures

PL/SQL Concepts 32
Functions − These subprograms return a single value; mainly used to compute and
return a value.
Procedures − These subprograms do not return a value directly; mainly used to perform
an action.

PL/SQL Concepts 33
PL/SQL Concepts 34
Creating a Function

PL/SQL Concepts 35
Creating a Function

PL/SQL Concepts 36
Creating a Function

PL/SQL Concepts 37
Creating a Function

PL/SQL Concepts 38
Calling a Function
•While creating a function, you give a definition of what the
function has to do.
•To use a function, you will have to call that function to
perform the defined task.
•When a program calls a function, the program control is
transferred to the called function.
•A called function performs the defined task and when its
return statement is executed or when the last end
statement is reached, it returns the program control back to
the main program.

PL/SQL Concepts 39
Calling a Function

PL/SQL Concepts 40
Creating a Procedure
 A procedure is created with the CREATE OR REPLACE PROCEDURE statement.

PL/SQL Concepts 41
Creating a Procedure

PL/SQL Concepts 42
PL/SQL Concepts 43
PL/SQL Concepts 44
Stored procedure
CREATE OR REPLACE PROCEDURE
INCREASE_SALARY(E IN NUMBER, AMT IN NUMBER, S OUT NUMBER)
IS
BEGIN
UPDATE EMP SET SAL= SAL+AMT;
WHERE EMP_NO = E;
COMMIT;

SELECT SAL INTO S FROM EMP WHERE EMP_NO = E;


END;

PL/SQL Concepts 45
Stored procedure
 A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
 So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it.
 You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.
 A stored procedure (proc) is a group of PL/SQL statements that performs
specific task.
 A procedure has two parts, header and body.
 The header consists of the name of the procedure and the parameters passed
to the procedure.
 The body consists of declaration section, execution section and exception
section.
 A procedure may or may not return any value. A procedure may return more
than one value.
PL/SQL Concepts 46
Stored procedure
 Create:-It will create a procedure.
 Replace :- It will re-create a procedure if it already exists.
 We can pass parameters to the procedures in three ways.
1. IN-parameters: - These types of parameters are used to send values to
stored procedures.
2. OUT-parameters: - These types of parameters are used to get values from
stored procedures. This is similar to a return type in functions but
procedure can return values for more than one parameters.
3. IN OUT-parameters: - This type of parameter allows us to pass values into
a procedure and get output values from the procedure.

PL/SQL Concepts 47
Stored procedure
 AS indicates the beginning of the body of the procedure.
 sql_statement contains the SQL query. (select, insert, update or
delete)
 The syntax within the brackets [ ] indicates that they are optional.
 By using CREATE OR REPLACE together the procedure is created if
it does not exist and if it exists then it is replaced with the current
code.

PL/SQL Concepts 48
Advantages of stored procedure
 Security:- We can improve security by giving rights to selected
persons only.
 Faster Execution:- It is precompiled so compilation of procedure
is not required every time you call it.
 Sharing of code:- Once procedure is created and stored, it can be
used by more than one user.
 Productivity:- Code written in procedure is shared by all
programmers. This eliminates redundant coding by multiple
programmers so overall improvement in productivity.

PL/SQL Concepts 49
Stored Procedure Example
Customers
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitució
helados n 2222

3 Antonio Moreno Antonio Mataderos México D.F. 05023 Mexico


Taquería Moreno 2312

4 Around the Thomas Hardy 120 London WA1 1DP UK


Horn Hanover
Sq.
5 Berglunds Christina Berguvsväg Luleå S-958 22 Sweden
snabbköp Berglund en 8

PL/SQL Concepts 50
Example of stored procedure
A Stored procedure that accepts two numbers and return addition,
subtraction, multiplication and division of two numbers or in other
words a stored procedure to return multiple values through arguments.

PL/SQL Concepts 51
Example of stored procedure

PL/SQL Concepts 52
Example of stored procedure

PL/SQL Concepts 53
Cursor

PL/SQL Concepts 54
Cursor
 Cursor is a memory (work) area that a oracle engine uses for its internal
processing for executing and storing the results of SQL statement, and this work
area is reserved for SQL’s operations also called Oracle’s Private area or CURSOR
 Cursors are database objects used to traverse the results of a select SQL query.
 It is a temporary work area created in the system memory when a select SQL
statement is executed.
 This temporary work area is used to store the data retrieved from the database,
and manipulate this data.
 It points to a certain location within a record set and allow the operator to
move forward (and sometimes backward, depending upon the cursor type).
 We can process only one record at a time.
 The set of rows the cursor holds which is called the active set (active data set).
 Cursors are often criticized for their high overhead.

PL/SQL Concepts 55
Cursor
Example:
 When a user fires a select statement as:
SELECT empno, ename, job,..
FROM emp
WHERE deptno = 10;
 All the rows returned by the query are stored in the cursor at the Server
and will be as displayed at the client end.
 When oracle engine executes the above query as a result some memory
area is reserved and is fed with the result of the SQL statement.

PL/SQL Concepts 56
Types of cursor
 There are two types of cursors in PL/SQL:
1. Implicit cursors:
• These are created by default by SQL itself when DML statements like, insert,
update, and delete statements are executed.
• They are also created when a SELECT statement returns just one row.
• We cannot use implicit cursors for user defined work.
2. Explicit cursors:
• Explicit cursors are user defined cursors written by the developer.
• They can be created when a SELECT statement returns more than one row.
• 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.

PL/SQL Concepts 57
General Cursor Attributes

PL/SQL Concepts 58
Implicit Cursor 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
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
4 returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.

PL/SQL Concepts 59
PL/SQL Concepts 60
PL/SQL Concepts 61
Use of SQL%ROWCOUNT
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/

PL/SQL Concepts 62
Steps to manage explicit cursor
1. Declare Cursor: A cursor is declared by defining the SQL
statement that returns a result set.
2. Open: A Cursor is opened and populated by executing the SQL
statement defined by the cursor.
3. Fetch: When the cursor is opened, rows can be fetched from the
cursor one by one or in a block to perform data manipulation.
4. Close: After data manipulation, close the cursor explicitly.
5. Deallocate: Finally, delete the cursor definition and release all
the system resources associated with the cursor.

PL/SQL Concepts 63
Explicit cursor

 An explicit cursor is defined in the declaration section of the


PL/SQL Block.
 It is created on a SELECT Statement which returns more than one
row. A suitable name for the cursor.
 General syntax for creating a cursor:
CURSOR cursor_name IS select_statement;
• cursor_name – A suitable name for the cursor.
• select_statement – A select query which returns multiple rows

PL/SQL Concepts 64
How to use explicit cursor?
 There are four steps in using an Explicit Cursor.
1. DECLARE the cursor in the Declaration section.
2. OPEN the cursor in the Execution Section.
3. FETCH the data from the cursor into PL/SQL variables or records in the
Execution Section.
4. CLOSE the cursor in the Execution Section before you end the PL/SQL
Block.

PL/SQL Concepts 65
Syntax of explicit cursor
DECLARE variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;

PL/SQL Concepts 66
Example of cursor

PL/SQL Concepts 67
Example of cursor

PL/SQL Concepts 68
Cursor FOR Loop

PL/SQL Concepts 69
Cursor FOR Loop

PL/SQL Concepts 70
Cursor FOR Loop

PL/SQL Concepts 71
Cursor FOR Loop

PL/SQL Concepts 72
Cursors with Parameters

PL/SQL Concepts 73
Cursors with Parameters

PL/SQL Concepts 74
Exception Handling

PL/SQL Concepts 75
Exception Handling
 An exception is an error which disrupts the normal flow of
program instructions. PL/SQL provides us the exception block
which raises the exception thus helping the programmer to find
out the fault and resolve it.
 Following is a general syntax for exception handling:

PL/SQL Concepts 76
Exception Handling
 Note: “When others” keyword should be used only at the end of
the exception handling block as no exception handling part
present later will get executed as the control will exit from the
block after executing the WHEN OTHERS.

 There are two types of exceptions −


• System-defined exceptions
• User-defined exceptions

PL/SQL Concepts 77
System-defined exceptions
• System defined exceptions: These exceptions are
predefined in PL/SQL which get raised WHEN
certain database rule is violated.
Exception Name Reason Error
Number
CURSOR_ALREADY_ When you open a cursor that is already open. ORA-06511
OPEN
INVALID_CURSOR When you perform an invalid operation on a ORA-01001
cursor like closing a cursor, fetch data from a
cursor that is not opened.

NO_DATA_FOUND When a SELECT...INTO clause does not return any ORA-01403


row from a table.
TOO_MANY_ROWS When you SELECT or fetch more than one row ORA-01422
into a record or variable.
ZERO_DIVIDE When you attempt to divide a number by zero. ORA-01476

PL/SQL Concepts 78
System-defined exceptions: Example-1
1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type; ID NAME AGE ADDRESS SALARY
5. BEGIN
1 Ramesh 23 Allahabad 20000
6. SELECT name, address INTO c_name, c_addr
7. FROM customers 2 Suresh 22 Kanpur 22000
8. WHERE id = c_id; 3 Mahesh 24 Ghaziabad 24000
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name); 4 Chandan 25 Noida 26000
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
5 Alex 21 Paris 28000
11. EXCEPTION
6 Sunita 20 Delhi 30000
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;

PL/SQL Concepts 79
System-defined exceptions: Example-2
/* Exception handling for TOO_MANY_ROWS */

DECLARE

v_lname employees.last_name%type;

BEGIN

SELECT last_name INTO v_lname

FROM employees

WHERE first_name = 'John';

DBMS_OUTPUT.PUT_LINE ('Last name is :' || v_lname);

EXCEPTION

WHEN TOO_MANY_ROWS THEN

DBMS_OUTPUT.PUT_LINE (' Your SELECT statement retrieved multiple rows. Consider using a
cursor.');

END;

PL/SQL Concepts 80
User-defined exceptions
 User defined exceptions: PL/SQL allows user to define their own
exceptions according to the need of user program.

 A user-defined exception must be declared and then raised explicitly, using


either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.

 The syntax for declaring an exception is −

PL/SQL Concepts 81
User-defined exceptions: Example-1
 Divide non-negative integer x by y such that the result is greater
than or equal to 1.
 From the given question we can conclude that there exist two
exceptions
• Division by zero.
• If result is greater than or equal to 1 means y is less than or equal to x.

PL/SQL Concepts 82
User-defined exceptions: Example-1
1. DECLARE
2. x integer:=&x; /*taking value at run time*/
3. y integer:=&y;
16. EXCEPTION
4. div float;
17. WHEN ex1 THEN
5. ex1 EXCEPTION;
18. dbms_output.put_line('Error');
6. ex2 EXCEPTION;
19. dbms_output.put_line('division by zero
7. BEGIN
not allowed');
8. IF y=0 then
20.WHEN ex2 THEN
9. raise ex1;
21. dbms_output.put_line('Error');
10. ELSIF y > x then
22. dbms_output.put_line('y is greater than
11. raise ex2;
x please check the input');
12. ELSE
23.END;
13. div:= x / y;
14. dbms_output.put_line('the result is '|| div);
15. END IF;

PL/SQL Concepts 83
User-defined exceptions: Example-2

PL/SQL Concepts 84
Database Triggers

PL/SQL Concepts 85
Database triggers
 A trigger is a PL/SQL block structure which is triggered (executed)
automatically when DML statements like Insert, Delete, and Update is
executed on a table.
 In other words, A database trigger is a stored procedure that is fired
when an INSERT, UPDATE, or DELETE statements is issued against the
associate table.
 The name trigger is appropriate, as these are triggered (fired) whenever
the above-mentioned commands are executed.
 A trigger defines an action the database should take when some
database related event occurs.
 A trigger is automatically executed without any action required by the
user.
• A stored procedure on other hand needs to be explicitly invoked.
• This is the main difference between a trigger and a stored procedure.
PL/SQL Concepts 86
Database triggers

Triggers are written to be executed in response to any of the following events −


• A database manipulation (DML) statement
(DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement
(CREATE, ALTER, or DROP).
• A database operation
(SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

PL/SQL Concepts 87
PL/SQL Concepts 88
Use of Database Triggers

PL/SQL Concepts 89
Parts of a Trigger

Types of Triggers

PL/SQL Concepts 90
Row Level Triggers
 Row level triggers execute once for each row in a transaction.
 The commands of row level triggers are executed on all rows
that are affected by the command that enables the trigger.
 For example,
• if an UPDATE statement updates multiple rows of a table, a row
trigger is fired once for each row affected by the UPDATE
statement.
• If the triggering statement affects no rows, the trigger
is not executed at all.
• Row level triggers are created using the FOR EACH ROW clause
in the CREATE TRIGGER command.

PL/SQL Concepts 91
Application of row level trigger

PL/SQL Concepts 92
Statement Level Triggers
• Statement level triggers are triggered only once
for each transaction.
• For example
• when an UPDATE command update 15 rows,
the commands contained in the trigger are
executed only once, and not with every
processed row.
• Statement level trigger are the default types
of trigger created via the CREATE TRIGGER
command.

PL/SQL Concepts 93
Before and After Trigger

PL/SQL Concepts 94
PL/SQL Concepts 95
Logon triggers
 This type of trigger is executed against a LOGON event before a
user session is established to the SQL Server.

PL/SQL Concepts 96
Database triggers
 When triggers can be used,
• Based on change in one table, we want to update
other table.
• Automatically update derived columns whose values
change based on other columns.
• Logging.
• Enforce business rules.

PL/SQL Concepts 97
Triggers (syntax)
 CREATE [OR ALTER OR REPLACE] TRIGGER trigger_name
ON table_name
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

AS
BEGIN
Executable statements
END;

PL/SQL Concepts 98
Triggers
 CREATE [OR ALTER OR REPLACE ] TRIGGER trigger_name:-
• This clause creates a trigger with the given name or overwrites
an existing trigger.
 ON table_name:-
• This clause identifies the name of the table or view to which
the trigger is related.
 { FOR | AFTER | INSTEAD OF }:-
• This clause indicates at what time the trigger should be fired.
Before executing DML statements or after executing DML
statements.

PL/SQL Concepts 99
Triggers
 { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } :-
• This clause determines on which kind of statement
the trigger should be fired.
• Either on insert or update or delete or combination of
any or all.
• More than one statement can be used together
separated by comma. The trigger gets fired at all the
specified triggering event.

PL/SQL Concepts 100


Triggers (syntax)

PL/SQL Concepts 101


Example of triggers-1
 Trigger to display a message when we perform insert
operation on student table.

CREATE TRIGGER student_msg


on Student
AFTER INSERT
AS
BEGIN
print ‘Record inserted successfully'
END;

PL/SQL Concepts 102


Example of triggers-1
 OUTPUT:- Trigger is created.
 Now when you perform insert operation on student table.
 SQL:> Insert into student values (101, ‘Raj’, ‘CE’);
 It displays following message after executing insert statement.
 Output:- Record inserted successfully
 We get message that “Record inserted successfully” it indicates
that trigger has executed after the insertion operation.

PL/SQL Concepts 103


Example of triggers-2
 Trigger to display a message when we perform insert, update or
delete operation on student table.

CREATE TRIGGER student_msg


on Student
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
print ‘One record is affected'
END;

PL/SQL Concepts 104


Example of triggers-2
 OUTPUT:- Trigger is created.
 Now when you perform insert, update or delete operation on
student table.
 SQL:> Insert into student values (102, ‘Raj’, ‘CE’); OR
Update student set Dept=‘EC’ where Rno=101 OR
Delete from student where Rno=101
 It displays following message after executing insert, update or
delete statement.
 Output:- One record is affected
 We get message that “One record is affected” it indicates that
trigger has executed after the insertion operation.

PL/SQL Concepts 105


PL/SQL Concepts 106
PL/SQL Concepts 107
PL/SQL Concepts 108
PL/SQL Concepts 109
PL/SQL Concepts 110
PL/SQL Concepts 111
PL/SQL Concepts 112
PL/SQL Concepts 113
PL/SQL Concepts 114
Thank you

PL/SQL Concepts 115

You might also like