PL SQL 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

PL/SQL

PL/SQL Procedure
• The PL/SQL stored procedure or simply a procedure is a PL/SQL block which
performs one or more specific tasks.
The procedure contains a header and a body.
Header: The header contains the name of the procedure and the
parameters or variables passed to the procedure.
Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.
Creating a Procedure
• A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows −
Where,
procedure-name specifies the name of the
CREATE [OR REPLACE] PROCEDURE procedure.
[OR REPLACE] option allows the modification
procedure_name of an existing procedure.
The optional parameter list contains name,
[(parameter_name [IN | OUT | IN OUT] mode and types of the
type [, ...])] parameters. IN represents the value that will
be passed from outside and OUT represents
{IS | AS} the parameter that will be used to return a
BEGIN value outside of the procedure.
procedure-body contains the executable part.
< procedure_body > The AS keyword is used instead of the IS
END procedure_name; keyword for creating a standalone procedure.
Procedure Example:
CREATE OR REPLACE PROCEDURE
hello
AS
BEGIN
dbms_output.put_line('Hello
World!');
END;
begin
hello;
end;
Procedure Drop

DROP PROCEDURE hello;

begin
hello;
end;
Parameter Modes in PL/SQL Subprograms

SLNO Parameter Mode & Description


1 IN An IN parameter lets you pass a value to the subprogram.
It is a read-only parameter.
2 OUT An OUT parameter returns a value to the calling program.
The actual parameter must be variable and it is passed
by value.
3 IN OUT An IN OUT parameter passes an initial value to a
subprogram and returns an updated value to the caller.
This parameter is used for both giving input and for
getting output from the subprograms.
Example 1
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;
Example 2
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
PL/SQL Function
• The PL/SQL Function is very similar to PL/SQL Procedure. The main difference
between procedure and a function is, a function must always return a value,
and on the other hand a procedure may or may not return a value. Except
this, all the other things of PL/SQL procedure are true for PL/SQL function too.
CREATE [OR REPLACE] FUNCTION
Function_name: specifies the name of the
function_name [parameters] function.
[(parameter_name [IN | OUT | IN OUT] [OR REPLACE] option allows modifying an
existing function.
type [, ...])] The optional parameter list contains
RETURN return_datatype name, mode and types of the parameters.
{IS | AS} IN represents that value will be passed
from outside and OUT represents that this
BEGIN parameter will be used to return a value
< function_body > outside of the procedure.
END [function_name];
PL/SQL Function
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the
function.
• Function_body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone
function.
PL/SQL Function Example 1
create or replace function adder(n1 in number, n2 in num
ber)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;

DECLARE
n3 number(2);
BEGIN
n3 := adder(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
DECLARE
a number;
PL/SQL Function Example 2
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;

RETURN z;
END;
BEGIN
a:= 23;
b:= 45;

c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
Write PL/SQL procedure for an application using Find the total strength of
students in a class using functions (Labset A 11)
DECLARE
Create table customer(custid number, c number(2);
custname varchar(20), custaddress BEGIN
varchar(20) ); c := total_Customers();
dbms_output.put_line('Total no. of Customers: ' || c);
Insert into customer values(121,'Anu','Bangalore'); END;
insert into customer values(122,'Azar','Chennai');
insert into customer values(123, 'Ajay','Mysore');
insert into customer values(124, 'arun','kerala');

CREATE OR REPLACE FUNCTION total_Customers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customer;
RETURN total;
END;
PL/SQL 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; for example, the number of rows processed, etc.
• 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 referred to as the active set.
Implicit Cursors
• The implicit cursors are automatically generated by Oracle while an SQL
statement is executed, if you don't use an explicit cursor for the statement.
• These are created by default to process the statements when DML statements
like INSERT, UPDATE, DELETE etc. are executed.
• The attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT
are available.
Implicit Cursors
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect at
least one row or more rows or a SELECT INTO statement returned one or more rows.
Otherwise it returns FALSE.

%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect no
row, or a SELECT INTO statement return no rows. Otherwise it returns FALSE. It is a
just opposite of %FOUND.

%ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is automatically
closed after executing its associated SQL statements.

%ROWCOUNT It returns the number of rows affected by DML statements like INSERT, DELETE, and
UPDATE or returned by a SELECT INTO statement.
Write PL/SQL procedure for an application using cursors. (PART A 10)
Create table customers
DECLARE
(
total_rows number(2);
c_id number,
BEGIN
c_name varchar(20),
UPDATE customers
c_addr varchar(20),
SET c_salary = c_salary + 5000;
c_salary number(20)
IF sql%notfound THEN
);
dbms_output.put_line('no customers updated');
Insert into customers values(222,'Arun','Chennai',20000); ELSIF sql%found THEN
Insert into customers values(223,'Vara','Bangalore', 30000); total_rows := sql%rowcount;
Insert into customers values(224,'Zain','Mysore', 40000); dbms_output.put_line( total_rows || 'customers updated
Insert into customers values(225,'Dani','Chennai', 50000); ');
Insert into customers values(226,'Shoba','Kerala', 60000); END IF;
END;
select * from customers;
Write PL/SQL procedure for an application using cursors.
DECLARE
select * from customers; total_rows number(2);
BEGIN
UPDATE customers
SET c_salary = c_salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
truncate table customers dbms_output.put_line( total_rows || 'customers
updated ');
END IF;
END;
Explicit Cursors
• The Explicit cursors are defined by the programmers to gain more control over
the context area. These cursors 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 of explicit cursor:
CURSOR cursor_name IS select_statement;
• Steps:
You must follow these steps while working with an explicit cursor.
1. Declare the cursor to initialize in the memory.
2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.
Explicit Cursors DECLARE
c_id customers.id%type;
ID NAME AGE ADDR SALA c_name customers.name%type;
ESS RY c_addr customers.address%type;
1 Rames 23 Allahab 20000 CURSOR c_customers is
h ad SELECT id, name, address FROM customers;
2 Suresh 22 Kanpur 22000 BEGIN
OPEN c_customers;
3 Mahes 24 Ghazia 24000
h bad LOOP
FETCH c_customers into c_id, c_name, c_addr;
4 Chand 25 Noida 26000 EXIT WHEN c_customers%notfound;
an
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr
5 Alex 21 Paris 28000 );
6 Sunita 20 Delhi 30000 END LOOP;
CLOSE c_customers;
END;
%isopen Cursors declare
cursor c1 is select * from customer;
create table customer(id a customer%rowtype;
number(5), name varchar2(20)) begin
open c1;
if c1%isopen then
insert into customer values(101,'arun')
dbms_output.put_line('cursor is open');
insert into customer values(102,'ansh')
else
dbms_output.put_line('cursor is not
open');
end if;
close c1
end
%isopen Cursors
declare
cursor c1 is select * from customer;
a customer%rowtype;
begin

if c1%isopen then
dbms_output.put_line('cursor is open');
else
dbms_output.put_line('cursor is not
open');
end if;

end
PL/SQL Exception Handling Syntax:
DECLARE
• An error occurs during the <declarations section>

program execution is called BEGIN


<executable command(s)>
Exception in PL/SQL.
EXCEPTION
• PL/SQL facilitates <exception handling goes here >
programmers to catch such WHEN exception1 THEN

conditions using exception exception1-handling-statements


WHEN exception2 THEN
block in the program and an
exception2-handling-statements
appropriate action is taken WHEN exception3 THEN
against the error condition. exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Some of the PL/SQL Exceptions
Exception Description
INVALID_CURSOR It is raised when attempts are made to make a cursor
operation that is not allowed, such as closing an
unopened cursor.
NO_DATA_FOUND It is raised when a select into statement returns no
rows.
VALUE_ERROR It is raised when an arithmetic, conversion, truncation,
or size-constraint error occurs.
ZERO_DIVIDE It is raised when an attempt is made to divide a number
by zero.
STORAGE_ERROR It is raised when PL/SQL ran out of memory or memory
was corrupted.
PL/SQL Exception Handling
DECLARE
Consider the following customer table: c_id customers.id%type := 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE (‘Name: ‘|| c_name);
DBMS_OUTPUT.PUT_LINE (‘Address: ‘ || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line(‘No such customer!’);
WHEN others THEN
dbms_output.put_line(‘Error!’);
END;
/
PL/SQL Exception Handling
DECLARE
Consider the following customer table: c_id customers.id%type := 2;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE (‘Name: ‘|| c_name);
DBMS_OUTPUT.PUT_LINE (‘Address: ‘ || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line(‘No such customer!’);
WHEN others THEN
dbms_output.put_line(‘Error!’);
END;
/
9. Write PL/SQL procedure for an application using exception
handling. (Part A 9)
DECLARE
N number;
BEGIN
N:=10/0;
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Zero
Divide Error');
END;
PL/SQL Packages
A package is a schema object that groups logically related PL/SQL types,
variables and subprograms.
Parts of a package:
1. Package specification
2. Package body or definition
PL/SQL Packages
Package specification:
• The package specification is the package interface which declares the types,
variables, constants, exceptions, cursors and subprograms that can be
referenced from outside the package.
Syntax of package specification:

CREATE PACKAGE package_name AS


PROCEDURE procedure_name;
END package_name;
PL/SQL Packages
Package body or definition:
• The package body or definition defines the queries for the cursors and the
code for the subprograms.

Syntax of body or definition:

CREATE OR REPLACE PACKAGE BODY package_name AS


PROCEDURE procedure_name IS //procedure body
END procedure_name;
END package_name; /
PL/SQL Packages Example
CREATE PACKAGE mypackage AS
Procedure study (p varchar2);
Procedure exam (q varchar2);
END mypackage;
CREATE OR REPLACE PACKAGE BODY mypackage AS BEGIN
--procedure implemented mypackage.study('If you study');
Procedure study (p varchar2) AS mypackage.exam ('You will pass exam');
BEGIN
DBMS_OUTPUT.PUT_LINE ('First Procedure: ' || p); END;
END;
--procedure implemented
Procedure exam (q varchar2) AS
BEGIN
DBMS_OUTPUT.PUT_LINE ('Second Procedure: ' || q);
END;
END;
12. Write a PL/SQL procedure for an application using package. Perform few
PL/SQL string operations.(PART A 12)
CREATE PACKAGE mypackage AS BEGIN
Procedure position(p varchar2); mypackage.position('College');
Procedure concatination(q varchar2,r varchar2); mypackage.concatination('New ','Horizon');
END mypackage;
END;
CREATE OR REPLACE PACKAGE BODY mypackage AS
--procedure implemented
Procedure position(p varchar2) AS
BEGIN
DBMS_OUTPUT.PUT_LINE ('Character is at: ' || INSTR(p,'g')||
'th position');
END;
--procedure implemented
Procedure concatination(q varchar2,r varchar2) AS
BEGIN
DBMS_OUTPUT.PUT_LINE ('Concatenated string is: ' ||
concat(q,r));
END;
END;

You might also like