DMS Chapter 4 PL-SOL Programming Notes
DMS Chapter 4 PL-SOL Programming Notes
DMS Chapter 4 PL-SOL Programming Notes
Wagh Polytechnic,Nashik
INTRODUCTION
PL/SQL stand for Procedural Language / Structured Query Language
An extension to SQL with design features of programming languages.
Allows user to write a program to do the various operations on databases.
PL/SQL is a combination of SQL statements with the programming Language.
ADVANTAGES OF PL/SQL
1) Procedural Language Capability
PL/SQL consists of Procedural language such as conditional statement (if statement )
and loops like (FOR loop).
3) Improved Performance
PL/SQL allows you to logically combine multiple SQL statements as one unit or block.
PL/SQL engine Processes multiple SQL statements simultaneously as a single block,
thereby reducing network traffic, and provides high performance for the application.
4) Portability
Applications written in PL/SQL are portable to any computer hardware and operating
systems.
You can write portable program packages and create libraries that can be reused on
Oracle databases in different environments.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
5) Exception Handling
An exception is an error that occurs in the database or in a user‟s program during
runtime.
Examples of errors include: hardware or network failures, application logic errors, data
integrity errors, and so on.
You can prepare for errors by writing exception handling code.
Exception handling code tells your program what to do in the event of an exception.
PL/SQL allows you to handle database and program exceptions efficiently. You can
define separate blocks for dealing with exceptions.
Declare Section - This is optional section starts with key word „declare‟. Declare section is used
to declare variables, constants, cursor etc.
Execution Section – This Section is Compulsory (mandatory). This section is starts with
keyword „begin‟ and ends with „end‟. The Program‟s Logic is written in this section.
Exception Handling Section- This section is optional and starts with the keyword „exception‟. It
is used to write the code for handling the errors in the program.
DECLARE (Optional)
/*Variables, cursors, user-defined exceptions
BEGIN (Mandatory)
/* SQL statement, PL/SQL statements
EXCEPTION (Optional)
/* Actions to perform when errors occur
END; (Mandatory)
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
PL/SQL DATATYPES
1. Char(size): This data type is used to store strings values of fixed length. The size in
brackets determines the number of characters the cell can hold. It can hold maximum 255
characters.
Example : char(50)
2. varchar (size)/varchar2(size): This data type is used to store variable length
alphanumeric data. The maximum this data type can hold up to 4000 characters.
Example : varchar2(80)
3. Date: This data type is used to represent date and time. The Default format is :
DD-MM-YY
Example : ‘20-oct-14’
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
4. Number(p,s): This data type is used to store fixed or floating point numbers. P is the
precision & S specifies scale. The maximum precision is 38 digits.
Example : number(5,2) , number(5).
5. Long: This data type is used to store variable length character strings containing up to 2
GB. Only one long Column allowed per Table.
6. RAW :- This data type is used to store Binary Data such as Digitized, Picture or Image
Maximum storage up to 255 bytes.
7. RAW LONG : - This data type is used store Binary data such as as Digitized, Picture or
Image Maximum storage up to 2 GB.
REFERENCE VARIABLES
Reference variables directly reference specific database column or row
Reference variables assume data type of associated column or row
%TYPE data declaration syntax:
variable_name tablename.fieldname%TYPE;
The (%TYPE) reference data type specifies a variable that references a single Database
field.
Example:
Empid emp.empno%TYPE;
the empid variable assumes a data type of VARCHAR2(30), because this is the data type of the
empno in the EMP table.
GENERATING OUTPUT
SET SERVEROUTPUT ON;
Put the command at the beginning of the program, right before the declaration section.
DISPLAYING OUTPUT
Syntax:
DBMS_OUTPUT.PUT_LINE(<string>);
In which PUT_LINE is the procedure to generate the output on the screen, and
DBMS_OUTPUT is the package to which the PUT_LINE belongs.
BEGIN
dbms_output.put_line(„Welcome To PL/SQL Programming‟);
END;
/
Output:
Welcome To PL/SQL Programming
PL/SQL procedure successfully completed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
OUTPUT
Enter value for val: 200
old 5: val:=& val;
new 5: val:=200;
the salary is increased by200
salary of ajay is12900
PL/SQL procedure successfully completed.
declare
no number(10);
sqr number:=1;
begin
no:=&no;
sqr:=no*no;
dbms_output.put_line(„Square of a number „ ||no||‟is‟||sqr);
end;
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
CONTROL STRUCTURES
Control structure is used for decision making and changing the control flow of the program.
1) Conditional Control
1. IF - THEN
2. IF – THEN- ELSE
3. IF –THEN –ELSE –IF
2) Iterative Control
1. LOOP
2. While LOOP
3. FOR LOOP
3) Sequential Control
1. GOTO Statement
1) Conditional Control
1. IF -THEN
An IF-THEN statement allows you to specify only one group of actions to take.
The simplest form of IF statement associated a condition with a sequence of statement
enclosed by the keyword THEN and END IF
If condition is TRUE then statement get execute, if False then if statement does nothing.
Syntax:
IF <condition> then
Statements;
End IF;
1. Program to find out whether second number is larger from two given
numbers.
SQL> declare
2 a number:=10;
3 b number:=20;
4 begin
5 if b > a then
6 dbms_output.put_line(' B is Big ');
7 end if;
8 end;
9 /
B is Big
PL/SQL procedure successfully completed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
2. IF – THEN- ELSE
If the value of condition is true, the statements run; otherwise, the else_statements run
Syntax:
IF <condition > then
statements;
Else
statements;
End if;
7 dbms_output.put_line(ch||'is a vowel');
8 else
9 dbms_output.put_line(ch||'is a not vowel');
10 end if;
11 end;
12 /
OUTPUT
Enter value for ch: i
old 4: ch:='&ch';
new 4: a:=„i';
i is a vowel
PL/SQL procedure successfully completed.
OUTPUT
Enter value for a: 20
Enter value for b: 30
Enter value for c: 40
C IS BIG
PL/SQL procedure successfully completed.
2) Iterative Control
Iterative control Statements are used when we want to repeat the execution of one or
more statements for specified number of times.
1) LOOP
2) WHILE LOOP
3) FOR LOOP
1. LOOP
A Simple Loop is used when a set of statements is to be executed at least once before the
loop terminates.
An EXIT condition must be specified in the loop, When the EXIT condition is satisfied
the process exits from the loop.
Syntax :
LOOP
statements;
EXIT WHEN condition;
END LOOP;
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
FLOWCHART OF LOOP
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
OUTPUT
2
4
6
8
10
PL/SQL procedure successfully completed
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
2. While Loop
A WHILE LOOP is used when a set of statements has to be executed as long as a
condition is true.
The condition is evaluated at the beginning of each iteration. The iteration continues
until the condition becomes false
Syntax:
WHILE <condition> LOOP
statements;
END LOOP;
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
OUTPUT
1
2
3
4
5
PL/SQL procedure successfully completed.
OUTPUT
Enter value for num: 5
old 6: num:=#
new 6: num:=5;
120
PL/SQL procedure successfully completed.
3. For Loop
A FOR LOOP is used to execute a set of statements for a predetermined number of
times.
Iteration occurs between the start and end integer values given.
Syntax:
FOR counter IN [reverse] val1..val2 LOOP
statements;
END LOOP;
val1 - Start integer value.
val2 - End integer value.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
OUTPUT
1
2
3
4
5
PL/SQL procedure successfully completed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
OUTPUT
55
PL/SQL procedure successfully completed.
OUTPUT
10
9
8
7
6
5
4
3
2
1
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
3)Sequential Control
The Goto to statement immediately transfer Program control unconditionally ( Without
checking Conditon ) to Label( Jump Location) Statement .
Goto to statement can not Branch into IF Statement, Loop statement.
Changes the flow of control within the block.
Entry point is marked using tag:
<<userdefined name>
GOTO Statement is used to jump to this label.
Syntax:
Begin
Statements;
GOTO Lablel_1;
Statements;
<<Lablel_1>>
Statements;
END;
Write a program to print the numbers 1 to 5 , and then print ,message as number is 5 label
is displayed
SQL> declare
2 i number;
3 begin
4 for i in 1..10 loop
5 dbms_output.put_line(i);
6 if (i=5) then
7 goto label1;
8 else
9 null;
10 end if;
11 end loop;
12 <<label1>>
13 dbms_output.put_line('As i=5, label1 is displayed');
14 end;
15 /
OUTPUT
1
2
3
4
5
As i=5, label1 is displayed
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
EXCEPTION HANDLING
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
1. ZERO_DIVIDE Exception
The ZERO_DIVIDE Exception (ORA-01476) occurs when a program attempts to
divide a number by zero
OUTPUT
Enter value for a: 6
old 6: a:=&a;
new 6: a:=6;
Enter value for b: 0
old 7: b:=&b;
new 7: b:=0;
divisor is zero
PL/SQL procedure successfully completed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
C001 RDM 48 1
C002 VB 45 2
C003 DSU 34 3
C004 PIC 40 4
2. NO_DATA_FOUND Exception
It is raised when a SELECT INTO statement returns no rows.
Handling NO_DATA_FOUND exception.
SQL> declare
2 c_id course.cid%type;
3 begin
4 select cid into c_id from course where sub='VBS';
5 Exception
6 when NO_DATA_FOUND then
7dbms_output.put_line(' Data is No Found by Select Query');
8 end;
9 /
OUTPUT
Data is No Found by Select Query
PL/SQL procedure successfully completed.
3. TOO_MANY_ROWS Exception
It is raised when s SELECT INTO statement returns more than one row.
Handling TOO_MANY_ROWS exception.
SQL> declare
2 c_id course.cid%type;
3 begin
4 select cid into c_id from course;
5 exception
6 when TOO_MANY_ROWS then
7 dbms_output.put_line(' Many Rows are Fetched.... ');
8 end;
9 /
OUTPUT
Many Rows are Fetched....
PL/SQL procedure successfully completed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
Syntax:
DECLARE
<exception_name> exception ;
BEGIN
<SQL Sentences>;
if <condition> Then
Raise <exception_name>
End if;
EXCEPTION
WHEN <exception_name> THEN
-Error handling statements/user defined action to be carried out;
END;
E.g. Program to Check the Duration if it is Less than 40 then raise user defined
exception
SQL> declare
2 my_exe Exception;
3 D1 course.duration%type;
4 begin
5 select duration into d1 from course where sid=3;
6 if d1 <40 then
7 raise my_exe;
8 end if;
9 exception
10 when my_exe then
11 dbms_output.put_line(' Duration is less than 40');
12 end;
13 /
OUTPUT
Duration is less than 40
PL/SQL procedure successfully completed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
RAISE_APPLICATION_ERROR
To display your own error message one can use the bulit in
RAISE_APPLICATION_ERROR.
Use negative number between -20000 to -20999 for the Error_number and the error
message should not exceed 512 character.
Syntax :
RAISE_APPLICATION_ERROR( error_number,’error message‟);
Example- IF data is not found for SID=6 then use Raise_application_error to Display
message
SQL >declare
1 dur course.duration%type;
2 begin
3 select duration into dur from course where sid=6;
4 Exception
5 when NO_DATA_FOUND then
6 Raise_application_error(-20100,'NO Data Found');
7 end;
8/
Output:
ERROR at line 1:
ORA-20100: NO Data Found
ORA-06512: at line 6
PL/SQL procedure successfully completed.
ERROR at line 1:
ORA-20202: divisor is zero
ORA-06512: at line 4
PL/SQL procedure successfully completed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
CURSORS
PL/SQL Cursor is Pointer that Points the results set of the SQL Query Against
database Table
Cursor is a temporary work area created in the system memory when SQL statement
is executed.
It is used to store the data retrieved from the database and manipulate this data.
The data stored in the cursor is called as Active Data Set.
A cursor can hold more than one row but can process only one row at a time.
Cursor is used with select Statement and store result.
Types of Cursor.
1)Implicit
2) Explicit
1) Implicit Curcors
Implicit cursors are created for every query made in Oracle Like Delete ,Update, Insert
,Select etc .
When we write command ,we use implicit cursors.
They are system generated cursors.
Oracle will perform the open, fetches, and close for you automatically.
Implicit cursors are used in statements that return only one row.
o The most recently opened cursor is called the “SQL%” Cursor.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
2) Explicit Cursor.
Cursors can be declared by a programmer within PL/SQL
They must be created when you are executing a SELECT statement that 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.
Cursor Is First Declared then Open, Once the Cursor open Fetch Data From Cursor,
Finally Close the Cursor.
1) Declare Cursor
Defines name and structure of cursor.
Syntax:
Cursor <cursor_name> IS Select statement ;
Example:
Cursor c1 is select name,marks from student1;
2) Open
Syntax:
Open <Cursor_name>;
Example:
open c1;
4) Close
Syntax:
close <Cursor_name>;
Example:
close c1;
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
General Syntax :
declare
Variable Declaration;
cursor <name_cursor> IS select statement ;
begin
open <name_cursor>;
fetch <name_cursor > into <Variable_name>;
Close <name_cursor>
end;
/
Consider table student1;
NO NAME MARKS
---------- -------------------- ----------
1 akash 85
2 nikita 65
3 puja 75
4 nisha 35
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
PROCEDURE
A procedure is named PL/SQL block perform one or more specific task .
Procedure consist of Header and Body .
Header – Contain name of Procedure and Parameter Passed to it.
Body - Contain Declaration ,Execution, Exception section Same AS PL/SQL
Syntax :
Create OR Replace Procedure < name_Procedure>
[ Parameter name [IN | OUT | IN OUT] Data_type ]
[ IS | AS ]
Variable declaration;
Constant declarations;
Begin
Pl/sql subprogram;
END < name_Procedure> ;
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
Calling of procedure
SQL> exec ins21(12,'punam',75);
record inserted
PL/SQL procedure successfully completed
Calling of procedure
SQL> exec select3('puja');
PL/SQL procedure successfully completed
Execution of procedure
SQL> Begin
Factorial(5);
End;
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
Deleteting a Proceduer
To delete Procedure use Following Command
DROP Procedure <Procedure_name>;
FUNCTION
Function is named PL/SQL Block that accept the value and Return only one value .
It is used for code reusability.
Syntax:
create or replace function <Function_name>(Parameter in Data type )
return Data Type
[IS | AS]
Variable declaration;
Constant declarations;
Begin
Pl/sql subprogram;
return Value ;
end <Funcation_name >;
SQL> declare
2 val1 number;
3 begin
4 val1 :=&val1;
5 dbms_output.put_line(„Square‟ || sqr(val1));
6 end;
7 /
Enter value for val1: 4
Square 16
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
addition is 40
PL/SQL procedure successfully completed.
Functions Procedures
A function must return a value back to caller. Procedure may or may not be return the value.
A function return only one value to the By defining the OUT parameters multiple values
calling PL/SQL block can be passed to the procedure.
Advantages of Function:
1. Code reusability feature can be used.
2. It saves time and cost.
3. Increases flexibility of the program.
4. Memory space required is less.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
Advantages of Procedure:
1. Security: Procedures offer more security.
2. Productivity: Avoids redundant code for common procedures in multiple applications.
3. Memory savings: Requires only one copy of the code for multiple users.
4. Performance: Precompiled code hence no compilation is required to execute a code.
5. Integrity and accuracy: As procedure is needed to be tested only once hence guarantee of
accurate result.
DATABASE TRIGGER
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement executed.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
1. Write a program which display pass or fail after insert, update of new marks
into student table using trigger
SQL> create trigger studtrigger
2 after insert or update on student1
3 for each row
4 begin
5 if(:new.marks<40) then
6 dbms_output.put_line('fail');
7 else
8 dbms_output.put_line('pass');
9 end if;
10 end;
11 /
Trigger created
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
EXAMPLE:
The price of a product changes constantly. It is important to maintain the history of the prices of
the products.
So we can create a trigger to Maintain the price history into 'product_price_history' table
when the price of the product is updated in the 'product' table.
2) Create the 'product_price_history' table which maintain the history of Price from
‘Product ‘ table ......
CREATE TABLE product_price_history (product_id number(5), product_name varchar2(32),
supplier_name varchar2 (32), unit_price number(7,2) );
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
Triggers are fired when particular SQL Procedures are executed when they are
command(DML) is executed called
Triggers have event and actions Procedures do not have event and
actions
Triggers are called implicitly Procedures are called explicitly
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
LOCKS
Lock are mechanism used to ensure data integrity while allowing maximum concurrent
access to data.
DML locks help to prevent damage caused by interference from simultaneous conflicting
DML or DDL operations.
Levels of lock:
1) Row level Lock
In this type of Lock Particular Row is Locked.
Row-level locks serve a primary function to prevent multiple transactions from
modifying the same row.
With row level locking only one row on the page is locked, the other rows are accessible.
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
2) Shared Lock
Shared lock allows the resource to be shared.
This sharing of resource depends on the operations that are involved.
Many users at a time can read the data. Share locks are used to avoid concurrent access
to the writers.
LOCKING STRATEGY
There are Two types of LOCKING Strategy :
1) Implicit Locking
2) Explicit Locking
1) Implicit Locking :
Oracle locking is fully automatic does not require user involvement .
Oracle Automatically lock table data while executing SQL statement .This type of
locking called Implicit Lock
Oracle Automatically lock the rows whenever user performs DML operation such as
INSERT ,UPDATE,DELETE .
2) Explicit Lock :
In this technique of lock on a table or its resources is given by a user is that‟s why it is
explicit Locking.
It‟s provided by user.
.
Question Bank:
1. Define cursor. List any two types of cursor. [2M] [Definition 1M, Types 1M]
2. Explain cursor with example. [4M] [4M explanation]
3. Which statement is used in PL/SQL to display the output? [2M] [2M Explanation]
4. Draw and explain in brief PL/SQL block. [4M] [ 2M Diagram,2M explanation]
5. Describe shared and exclusive lock in detail. [4M] [2M each]
6. What is database trigger? Compare database trigger and procedure and explain the use of
database trigger. [4M] [2M Explanation, 1M comparison, 1M use]
7. Explain following with syntax : a) Function b) Procedure [4M] [ 2M each]
8. Write PL/SQL program to display largest of 3 numbers. [4M] [4M Program]
9. Explain conditional control of PL/SQL. [4M]
10. Explain for loop in PL/SQL with Example. [4M] [2M explanation,2M Example]
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology
K.K. Wagh Polytechnic,Nashik
11. Explain loop in PL/SQL with Example. [4M] [2M explanation,2M Example]
12. Explain while loop in PL/SQL with Example. [4M] [2M explanation,2M Example]
13. Explain sequential control of PL/SQL. [4M]
14. Write PL/SQL program to display largest of 2 numbers. [4M] [4M Program]
15. What are exceptions? Explain its types. [4M] [2M explanation,2M Types]
16. What are cursors? Explain its types. [4M] [2M explanation,2M Types]
17. Write PL/SQL program to print the numbers from 1 to 15 using for loop. [4M]
[4M Program]
18. Explain triggers with the example. [4M] [2M explanation,2M Example]
19. What is trigger? List its types. (Definition - 1 Mark, Types -1Mark)
20. How to create triggers? State any two advantages of triggers. [4M] [2M explanation,2M
advantages]
21. Write PL/SQL program which handle zero_divide exception. [4M] [4M Program]
22. Write PL/SQL program which handle no_data_found exception and too_many_rows
exception. [4M] [2M each]
23. What is user defined exception? Write PL/SQL program which handle any user defined
exception [4M] [2M Explanation,2M Program]
24. What are the advantages of PL/SQL? [4M] [1M each]
25. What are the data types in PL/SQL? [4M] [1M each]
26. Write PL/SQL program and procedure to calculate factorial of the given number. [4M]
[4M Program]
27. Differentiate between function and procedure. [4M] [2M each]
28. What are various control structures statements used in PL/SQL. [4M] [1M each]
29. Write step by step syntax to create, open and close cursor in PL/SQL block. [4M]
[1M each]
30. List two advantages of each of following: a) functions b)procedures [4M] [2M each]
31. Write PL/SQL program to display square of any number. [4M] [4M Program]
32. Write PL/SQL program to display print even and odd number from given range.(Accept
range from user) [4M] [4M Program]
33. Write and explain the syntax of creating trigger. [4M] [2M each]
34. What is lock? Explain types of lock . [4M] [2M each]
35. Explain Locking strategy-Implicit &Explicit. [4M] [2M each].
Prepared By:
Ms. M. V. Upasani
Lecturer
Computer Technology