0% found this document useful (0 votes)
29 views33 pages

RDM Chapter-4

dms

Uploaded by

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

RDM Chapter-4

dms

Uploaded by

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

Database Management System(313302)

Chapter-4
PL/SQL Programming

Prepared By
Ms. H C. Kunwar
GHRCEM, Nagpur

RAISONI GROUP OF INSTITUTIONS


Introduction of PL/SQL

What is PL/SQL :
SQL stands for Structured Query Language
SQL allows you access and manipulate databases
SQL is an ANSI (American National Standards Institute) standard
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views

RAISONI GROUP OF INSTITUTIONS


Advantages of PL/SQL

Advantages of functions in PL/SQL :

1. Portability.
2. Modularized program development
3. High Performance, High Productivity, Scalability, Manageability.
4. Support for Object-Oriented Programming.
5. Support for Developing Web Applications
6. It improves performance against running SQL queries multiple times
7. It provides exception handling.
8. It provides built-in libraries & packages.
9. It integrates procedural constructs with SQL.

RAISONI GROUP OF INSTITUTIONS


Block Structure of PL/SQL
• PL/SQL Block Structure is given below
• Each PL/SQL program consists of SQL and PL/SQL statements which from a
PL/SQL block.
• A PL/SQL Block consists of four sections:
• The Declaration section : Declaration of memory variables used later in begin
section.
• The Begin…End section: SQL executable statements for manipulating table data
should be in BEGIN....END block.
• The Exception section : SQL and/or PL-SQL code to handle errors that may crop
up during execution of the above code block.

DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
RAISONI GROUP OF INSTITUTIONS
PL/SQL Data Types
Datatype of Pl/SQL
Datatype Description

CHAR Fixed-length character string with maximum size of 32,767


bytes
VARCHAR2 Variable-length character string with maximum size of 32,767
bytes
RAW Variable-length binary or byte string with maximum size of
32,767 bytes, not interpreted by PL/SQ
LONG Variable-length character string with maximum size of 32,760
bytes
LONG RAW Variable-length binary or byte string with maximum size of
32,760 bytes, not interpreted by PL/SQL
BLOB Used to store large binary objects in the database
CLOB Used to store large blocks of character data in the database
BFILE Used to store large binary objects in operating system files
outside the database

RAISONI GROUP OF INSTITUTIONS


Control Structure
Conditional Control : The IF statement
executes a sequence of statements Example :
depending on the value of a condition.
There are three forms of IF statements: SET SERVER OUTPUT ON
Declare
1. IF-THEN, A number(2) := 15;
2. IF-THEN-ELSE, Begin
3. IF-THEN-ELSIF. a:= 10;
IF(a<20)THEN
1. IF- THEN Statement : If the condition Dbms_output.put_line(‘a is less than 20’);
is true, the statements run otherwise, END IF;
it does nothing. The IF THEN dbms_output.put_line(‘ value of a is :’ !!a);
statement has this structure : END;
2. Syntax: /
IF condition THEN Output:
statements; A is less than 20
END IF; Value of a is : 15
PL/SQL procedure successfully completed

RAISONI GROUP OF INSTITUTIONS


Control Structure
2. IF- THEN ELSE Statement : If the
condition is true, the statements inside IF
gets executed otherwise ELSE part gets Example :
executed. The IF THEN ELSE statement has
this structure : SET SERVER OUTPUT ON
1. Syntax: Declare
IF condition THEN A number(2) := 100;
statements-1; Begin
ELSE IF(a<20)THEN
statement-2; Dbms_output.put_line(‘a is less than 20’);
END IF; ELSE
dbms_output.put_line(‘ a is greater than
20’);
END IF;
dbms_output.put_line(‘ value of a is :’ !!a);
END;
/

RAISONI GROUP OF INSTITUTIONS


Control Structure
3. IF- THEN ELSIF Statement : It allows
you to choose between several Example :
alternatives. The IF THEN ELSIF statement
has this structure : SET SERVER OUTPUT ON
1. Syntax: Declare
IF condition THEN A number(2) := 100;
statements-1; Begin
ELSIF IF(a<20)THEN
statement-2; Dbms_output.put_line(‘a is less than 20’);
ELSE ELSIF(a = 20)
END IF; dbms_output.put_line(‘ a is equal to 20’);
ELSE
dbms_output.put_line(‘ None of the value is
matching’);
END IF;
dbms_output.put_line(‘ value of a is :’ !!a);
END;
/

RAISONI GROUP OF INSTITUTIONS


Control Structure
4. CASE Statement : CASE statement Example :
selects one sequence of statement to
execute. A selector is an expression, the SET SERVER OUTPUT ON
value of which is used to select one of Declare
several alternatives. The CASE statement GRADE CHAR(1) := ‘A’ ;
has this structure : Begin
CASE GRADE
1. Syntax: WHEN ‘A’ THEN
CASE selector dbms_output.put_line(‘EXCELLENT’);
WHEN ‘VALUE1’ THEN S1; WHEN ‘B’ THEN
WHEN ‘VALUE2’ THEN S2; dbms_output.put_line(‘VERY GOOD’);
WHEN ‘VALUE3’ THEN S3; WHEN ‘C’ THEN
ELSE Sn; dbms_output.put_line(‘WELL DONE’);
END CASE; ELSE
dbms_output.put_line(No such grade’)
END IF;
dbms_output.put_line(‘ value of a is :’ !!a);
END;
/
RAISONI GROUP OF INSTITUTIONS
Control Structure

Q1. Write a program to find largest of two numbers.

Declare
A number(3);
B number(3);
Begin
A:=&A;
B:=&B;
If (A>B) then
Dbms_output.put_line(‟ Greater number=‟||A);
else
Dbms_output.put_line(‟ Greater number=‟||B);
End if;
End;

RAISONI GROUP OF INSTITUTIONS


Iterative Control Structure

1. LOOP : PL/SQL LOOP statement is an iterative control statement that allows to


execute a sequence of statements repeatedly like WHILE and FOR loop.
Syntax:
LOOP
sequence_of_statements;
END LOOP;
Example:
i number :=1;
Loop
dbms_out.put_line(‘Good Morning’);
i :=i+1;
Exit
when i=10
End Loop

RAISONI GROUP OF INSTITUTIONS


Iterative Control Structure

2. WHILE LOOP: If it is not known in advance how many times a sequence of


statements needs to execute. In such cases, one should use PL/SQL WHILE LOOP
statement.

Syntax:
WHILE condition LOOP
sequence_of_statements;
END LOOP;

Example:
i number := 1;
while (i<=10) Loop
dbms_output.put_line(i);
i :=i+1;
End Loop

RAISONI GROUP OF INSTITUTIONS


Iterative Control Structure
3. FOR LOOP : FOR loop is an iterative statement that execute a sequence of
statements a fixed number of times.

Syntax:

FOR loop_counter IN [REVERSE] lower_bound .. higher_bound LOOP


sequence_of_statements;
END LOOP;

Example:

For i in 1..10 loop


dbms_output.put_line(i);
end loop;

RAISONI GROUP OF INSTITUTIONS


Iterative Control Structure
Q1. Write a PL/SQL program to calculate factorial of a given number.

Program :
DECLARE
num number:=&num;
fact number:=1;
i number;
BEGIN
for i in 1..num loop
fact:=fact*i;
end loop;

RAISONI GROUP OF INSTITUTIONS


Iterative Control Structure
Q1. Write a PL/SQL program to find even or odd number number.

Program :
declare
n number:=&n;

begin
if mod(n,2)=0 then
dbms_output.put_line('number is even');
else
dbms_output.put_line('number is odd');
end if;
end;
/

RAISONI GROUP OF INSTITUTIONS


Iterative Control Structure
Q1. Write a PL/SQL program to check whether a given number is positive, negative or
zero.
Program :
DECLARE
num1 NUMBER := &get_num;
BEGIN
IF num1 < 0 THEN
DBMS_OUTPUT.PUT_LINE ('The number '||num1||' is a
negative number');
ELSIF num1 = 0 THEN
DBMS_OUTPUT.PUT_LINE ('The number '||num1||' is equal to
zero');
ELSE
DBMS_OUTPUT.PUT_LINE ('The number '||num1||' is a
positive number');
END IF;
END;
/ RAISONI GROUP OF INSTITUTIONS
Iterative Control Structure
Q1. Write a PL/SQL program to print numbers from 50 t0 60 using for loop.

Q2. Write a PL/SQL program to print numbers from 50 t0 60 in reverse order.

Q3. Write a PL/SQL CODE USING WHILE LOOP DISPLAY N EVEN NUMBERS.

RAISONI GROUP OF INSTITUTIONS


Exception Handling
Exception :

 Exception is nothing but an error.


• When the system throws a warning or has an error it can lead to an exception.
• Such exception needs to be handled and can be defined internally or user defined

Exception Handling : Exception handling is nothing but a code block in memory that
will attempt to resolve current exception condition.

Syntax:
DECLARE
Declaration section
…executable statement;
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements/user defined action to be carried out;
END;

RAISONI GROUP OF INSTITUTIONS


Contd..
Example :
Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code
to handle the exception as given below.
BEGIN
Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return any row.');
END;

RAISONI GROUP OF INSTITUTIONS


Contd..
Example :
DECLARE
A number:=20;
B number:=0;
C number;
BEGIN
dbms_output.put_line(‘First Num : ’||A);
dbms_output.put_line(‘Second Num : ’||B);
C:= A / B; --Raise built in Exception if B is 0
dbms_output.put_line(‘ Result ’ || C); -- and then Result will not be displayed
EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line(‘ Trying to Divide by zero :: Error ’);
END;

RAISONI GROUP OF INSTITUTIONS


Contd..
Types of Exception

1.Predefined Exception/system defined exception/named exception


 Are always automatically raised whenever related error occurs.
 The most common errors that can occurs during the execution of PL/SQL.
 Not declared explicitly. i.e. cursor already open, invalid cursor, no data found, zero divide
and too many rows etc.
 Programs are handled by system defined Exceptions.

2. User defined exception:

 It must be declare by the user in the declaration part of the block where the exception is
used.
 It is raised explicitly in sequence of statements using:
 Raise_application_error(errorno,errorname);

RAISONI GROUP OF INSTITUTIONS


Cursors

Cursor :
 A cursor is a temporary work area created in the system memory when a SQL
statement is executed.
 A work area used for internal processing in order to execute SQL statement is called
as a cursor.
 In other words, 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.
 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.
 Each cursor contains the followings 4 steps,
1. Declare Cursor: In this part we declare variables and return a set of values.
2. Open: This is the entering part of the cursor.
3. Fetch: Used to retrieve the data row by row from a cursor.
4. Close: This is an exit part of the cursor and used to close a cursor

RAISONI GROUP OF INSTITUTIONS


Contd..
Types Of Cursor
Cursors are classified as implicit cursor and explicit cursor.
1. Implict cursor: If database engine opens a cursor for internal processing, it is called as
implicit cursor.
Example of implicit cursor:
Begin
Update emp set salary= salary +500 where empno = &empno; ---[ implicit
cursor created]
If SQL%FOUND then --- [ checks whether data is fetched successfully in
implicit cursor or not]
Dbms_out.put_line(“Emp table modified”);
Else
Dbms_out.put_line(“Emp table modified”);
End if;
End;

RAISONI GROUP OF INSTITUTIONS


Contd..

• Implicit cursors are automatically created by Oracle whenever an SQL statement is


executed, when there is no explicit cursor for the statement.

• 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.

• In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has the attributes like %FOUND, %ISOPEN, %NOTFOUND, and
%ROWCOUNT.

RAISONI GROUP OF INSTITUTIONS


Contd..

The following table provides the description of the most used attributes

RAISONI GROUP OF INSTITUTIONS


Contd..
2. Explicit cursor:
 A user can open a cursor for processing data as required. Such user defined cursors are
known as 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.

syntax for creating an explicit cursor is :


Cursor cursor_name IS select_statement

Working with an explicit cursor involves four steps:


i. Declaring the cursor for initializing in the memory
ii. Opening the cursor for allocating memory
iii. Fetching the cursor for retrieving data
iv. Closing the cursor to release allocated memory

RAISONI GROUP OF INSTITUTIONS


Contd..
• Example of explicit cursor:
Declare
Cursor c1 is select empno, salary from emp Where deptno=10; [explicit cursor c1]
Ecode emp.empno%Type;
Sal emp.salary%Type;
Begin
Open c1; [explicit cursor c1 opened]
If c1%ISOPEN then
Loop
Fetch c1 into ecode,sal; [ values from cursor c1 fetched]
If c1% NOTFOUND then
Exit;
End if;
Update emp set salary = salary+500;
End Loop;
Close c1; [ explicit cursor c1 closed.]
Else
Dbms_out.put_line(“unable to open”);
End if;
End;
RAISONI GROUP OF INSTITUTIONS
Procedure

Procedure : It is named PL/SQL block which performs one or more specific task.

Syntax :-
CREATE OR REPLACE PROCEDURE procedure_name
[(parameter_name[IN | OUT | IN OUT] type […])] {IS | AS}
BEGIN
<PROCEDURE_BODY>
END procedure_name;

RAISONI GROUP OF INSTITUTIONS


Function

Function : A function is a logically grouped set of SQL and PL/SQL statements that perform a
specific task.. A function is same as a procedure except that it returns a value. A
function is created using the CREATE FUNCTION statement
Syntax:
CREATE OR REPLACE FUNCTION function_name(argument IN data type,…)
RETURN data type{ IS, AS}
Variable declarations;
Constant declarations;
BEGIN
PL/SQL subprogram body;
EXCEPTION
Exception pl/sql block;
END;

RAISONI GROUP OF INSTITUTIONS


Function

Example:
CREATE OR REPLACE FUNCTION Success_cnt
RETURN number
IS cnt number(7) := 0;
BEGIN
SELECT count(*) into cnt
FROM candidate where result='Pass';
RETURN cnt;
END;
/

RAISONI GROUP OF INSTITUTIONS


Database Triggers

Trigger :

 Trigger is a pl/sql block structure which is fired when a DML statements like Insert,
Delete, Update is executed on a database table.

 A trigger is triggered automatically when an associated DML statement is executed.

Purposes of database trigger :

1. To enforce complex integrity constraint


2. To customize complex security authorization
3. To maintain replicate table
4. To audit the process
5. To automatically perform an action when another concerned action takes place
6. Trigger are similar to stored procedure, but procedures are called explicitly and trigger
are called implicitly by oracle when concerned event occurs.
RAISONI GROUP OF INSTITUTIONS
Syntax for Creating & Deleting Trigger

1. Syntax for Creating a Trigger :

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) BEGIN --- sql statements END;

OR

CREATE TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF}


{INSERT | UPDATE | DELETE} [OF col_name] ON table_name [FOR EACH
ROW] WHEN (condition) BEGIN --- sql statements END;

2. Syntax for Deleting a Trigger :


Drop TRIGGER trigger_name;

RAISONI GROUP OF INSTITUTIONS


Contd..

Example for creating a trigger :

CREATE or REPLACE TRIGGER After_Update_Row_product


AFTER
insert On product
FOR EACH ROW
BEGIN
INSERT INTO product_check Values('After update, Row level',sysdate);
END;

RAISONI GROUP OF INSTITUTIONS

You might also like