0% found this document useful (0 votes)
63 views44 pages

Procedures & Functions

- The procedure DisplaySalary2 takes an employee ID as an IN parameter and salary as an OUT parameter. - It queries the employee salary based on ID and checks if it is greater than 15,000. - The salary is returned via the OUT parameter and displayed.

Uploaded by

Nakib Ahsan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
63 views44 pages

Procedures & Functions

- The procedure DisplaySalary2 takes an employee ID as an IN parameter and salary as an OUT parameter. - It queries the employee salary based on ID and checks if it is greater than 15,000. - The salary is returned via the OUT parameter and displayed.

Uploaded by

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

• PL/SQL stands for “Procedural Language extensions to the Structured

Query Language”. It is a procedural extension language for the structured


query language (SQL) and the Oracle relational database.
• PL/SQL allows developers to write code that is executed on the server-
side, enabling them to create database applications that can manipulate data
stored in Oracle databases.
Program Structures: Procedures and Functions

• A set of SQL and PL/SQL statements grouped together as a unit


(block) to solve a specific problem or perform a set of related
tasks.

• An anonymous block is a PL/SQL block that appears within


your application and it is not named or stored in the database.
In many applications, PL/SQL blocks can appear wherever SQL
statements can appear.

• A stored procedure is a PL/SQL block that Oracle stores in the


database and can be called by name from an application. May
or may not return a value.

• Functions always return a single value to the caller; procedures


do not return values to the caller.
PL/SQL Blocks

• PL/SQL code is built of Blocks, with a unique


structure.
• Anonymous Blocks: have no name (like scripts)
– can be written and executed immediately in
SQLPLUS
– can be used in a trigger
Anonymous Block Structure
DECLARE (optional)
/* Here you declare the variables you will use in this
block */
BEGIN (mandatory)
/* Here you define the executable statements (what the
block DOES!)*/
EXCEPTION (optional)
/* Here you define the actions that take place if an
exception is thrown during the run of this block */
END; (mandatory)
/ A correct completion of a block
will generate the following
Always put a new line with only :message
a / at the end of a block! (This
PL/SQL procedure successfully
tells Oracle to run the block)
completed
DECLARE
Syntax
identifier
identifier [CONSTANT]
[CONSTANT] datatype
datatype [NOT
[NOT NULL]
NULL]

[:=
[:= || DEFAULT
DEFAULT expr];
expr];
Notice that PL/SQL
Examples includes all SQL types,
…and more

Declare
Declare
birthday
birthday DATE;
DATE;
age
age NUMBER(2)
NUMBER(2) NOT
NOT NULL
NULL :=
:=
27;
27;
name
name VARCHAR2(13)
VARCHAR2(13) :=
:= 'Levi';
'Levi';
magic
magic CONSTANT
CONSTANT NUMBER
NUMBER :=
:= 77;
77;
valid
valid BOOLEAN
BOOLEAN NOT
NOT NULL
NULL :=
:=
Declaring Variables with the
%TYPE Attribute

Examples
Accessing column sname
in table Sailors

DECLARE
sname Sailors.sname%TYPE;
fav_boat VARCHAR2(30);
my_fav_boat fav_boat%TYPE :=
'Pinta';
...
Accessing
another variable
Declaring Variables with the
%ROWTYPE Attribute

Declare a variable with the type of a


Accessing
ROW of a table. table
Reserves

reserves_record Reserves%ROWTYPE;
And how do we access the fields in
reserves_record?

reserves_record.sid:=9;
Reserves_record.bid:=877;
In this example, we declared a variable named "emp" with the %ROWTYPE
attribute, which means it has the same data type as a row in the "employees" table.
We then assigned values to the variable and inserted it into the "employees" table
using the INSERT INTO statement.
Creating a Cursor
• We create a Cursor when we want to go over a
result of a query (like ResultSet in JDBC)
• Syntax Example:
sailorData is a
DECLARE variable that
cursor c is select * from sailors; can hold a
ROW from
sailorData sailors%ROWTYPE; the sailors
table
BEGIN
open c; Here the
fetch c into sailorData; first row of
sailors is
inserted into
sailorData
SELECT Statements
DECLARE
v_sname VARCHAR2(10);
v_rating NUMBER(3);
BEGIN
SELECT sname, rating
INTO v_sname, v_rating
FROM Sailors
WHERE sid = '112';
END;
/

• INTO clause is required.


• Query must return exactly one row.
• Otherwise, a NO_DATA_FOUND or TOO_MANY_ROWS
exception is thrown
SQL Cursor

SQL cursor is automatically created after each


SQL query. It has 4 useful attributes:
SQL%ROWCOUNT Number of rows affected by the
most recent SQL statement (an
integer value).
SQL%FOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement affects one or more rows.
SQL%NOTFOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement does not affect any rows.
SQL%ISOPEN Always evaluates to FALSE because
PL/SQL closes implicit cursors
immediately after they are executed.
SQL%ISOPEN
SQL%NOTFOUND
SQL%ROWCOUNT
Functions and Procedures
Functions and Procedures
• It is useful to put code in a function or
procedure so it can be called several times
• Once we create a procedure or function in a
Database, it will remain until deleted (like a
table).
Function and Procedure
Parameter Types
• Named PL/SQL programs (procedures and
functions) can take parameters.
• Parameters are optional on both procedures and
functions.
• Keep the parameter name under 30 characters,
they must start with a letter and contain no
spaces.
• There are three types of parameter: IN, OUT and
IN OUT.
18
Function and Procedure
Parameter Types (cont..)
• An IN parameter is used as an input only. An IN
parameter cannot be changed by the called program.
• An OUT parameter is initially NULL. The program
assigns the parameter a value and that value is
returned to the calling program.
• An IN OUT parameter may or may not have an initial
value. That initial value may or may not be modified by
the called program. Any changes made to the
parameter are returned to the calling program.

19
Function and Procedure
Parameter Types(cont..)
• Parameters are declared with data types but
without data type length or precision.
• a parameter may be declared as VARCHAR2
but it will not be declared with a length
component (VARCHAR2(30) would not be
valid).

20
Types of Parameters

Bordoloi and Bock


Creating Procedures
CREATE
CREATE [OR
[OR REPLACE]
REPLACE] PROCEDURE
PROCEDURE procedure_name
procedure_name
[(parameter1
[(parameter1 [mode1]
[mode1] datatype1,
datatype1,
parameter2
parameter2 [mode2]
[mode2] datatype2,
datatype2,
.. .. .)]
.)]
IS|AS
IS|AS
PL/SQL
PL/SQL Block;
Block;

• Modes:
– IN: procedure must be called with a value for the parameter.
Value cannot be changed
– OUT: procedure must be called with a variable for the parameter.
Changes to the parameter are seen by the user (i.e., call by
reference)
– IN OUT: value can be sent, and changes to the parameter are
seen by the user
• Default Mode is: IN
Example 13.4 – Procedure with No Parameters
CREATE OR REPLACE PROCEDURE DisplaySalary IS
temp_Salary NUMBER(10,2);
BEGIN
SELECT Salary INTO temp_Salary FROM Employee
WHERE EmployeeID = '01885';
IF temp_Salary > 15000 THEN
DBMS_OUTPUT.PUT_LINE ('Salary > 15,000.');
ELSE
DBMS_OUTPUT.PUT_LINE ('Salary < 15,000.');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('Employee not found.');
END DisplaySalary;
/

Bordoloi and Bock


Example 13.5 – Passing IN and OUT Parameters
CREATE OR REPLACE PROCEDURE DisplaySalary2(p_EmployeeID
IN CHAR, p_Salary OUT NUMBER) IS
v_Salary NUMBER(10,2);
BEGIN
SELECT Salary INTO v_Salary FROM Employee
WHERE EmployeeID = p_EmployeeID;
IF v_Salary > 15000 THEN
DBMS_OUTPUT.PUT_LINE ('Salary > 15,000.');
ELSE
DBMS_OUTPUT.PUT_LINE ('Salary <= 15,000.');
END IF;
p_Salary := v_Salary;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('Employee not found.');
END DisplaySalary2;

Bordoloi and Bock


Example 13.6 – Calling DisplaySalary2
DECLARE
v_SalaryOutput NUMBER := 0;
BEGIN
DisplaySalary2('01885', v_SalaryOutput);
DBMS_OUTPUT.PUT_LINE ('Actual salary: '
||TO_CHAR(v_SalaryOutput));
END;
/

Salary > 15,000.


Actual salary: 16250
PL/SQL procedure successfully completed.

Bordoloi and Bock


Procedures
Creation command Create or replace procedure sample1 as

Variable declarations v_num1 constant number := 2.5;


v_num2 constant number := 4;
v_product number;
BEGIN
Body of code v_product := v_num1 * v_num2;
END;
Example- what does this do?
Table mylog create
create or
or replace
replace procedure
procedure
num_logged
num_logged
logon_
(person
(person IN
IN mylog.who%TYPE,
mylog.who%TYPE,
who num
num OUT
OUT mylog.logon_num%TYPE)
mylog.logon_num%TYPE)
num
IS
IS
3 Pete BEGIN
BEGIN
select
select logon_num
logon_num
4 John
into
into num
num
2 Joe from
from mylog
mylog
where
where who
who == person;
person;
END;
END;
//
Inside the procedure body, a SELECT statement is used to retrieve the value of the
"logon_num" column from the "mylog" table, where the "who" column matches the "person"
parameter.
Calling the Procedure

declare
declare
howmany
howmany mylog.logon_num%TYPE;
mylog.logon_num%TYPE;
begin
begin
num_logged(‘John',howmany);
num_logged(‘John',howmany);
dbms_output.put_line(howmany);
dbms_output.put_line(howmany);
end;
end;
//

More procedures: p3.sql


Errors in a Procedure
• When creating the procedure, if there are errors in
its definition, they will not be shown
• To see the errors of a procedure called myProcedure,
type
SHOW ERRORS PROCEDURE myProcedure
in the SQLPLUS prompt
• For functions, type
SHOW ERRORS FUNCTION myFunction
Dropping a Procedure

• The SQL statement to drop a procedure is the


straight-forward DROP PROCEDURE
<procedureName> command.
• This is a data definition language (DDL) command,
and so an implicit commit executes prior to and
immediately after the command.

SQL> DROP PROCEDURE DisplaySalary2;


Procedure dropped.

Bordoloi and Bock


FUNCTIONS
• Functions are a type of stored code and are very similar
to procedures.
• The significant difference is that a function is a PL/SQL
block that returns a single value.
• Functions can accept one, many, or no parameters, but a
function must have a return clause in the executable
section of the function.
• The datatype of the return value must be declared in the
header of the function.
• A function is not a stand-alone executable in the way
that a procedure is: It must be used in some context. You
can think of it as a sentence fragment.
• A function has output that needs to be assigned to a
variable, or it can be used in a SELECT statement.

Bordoloi and Bock


Creating a Function

• Almost exactly like creating a procedure, but you


supply a return type
CREATE
CREATE [OR
[OR REPLACE]
REPLACE] FUNCTION
FUNCTION
function_name
function_name
[(parameter1
[(parameter1 [mode1]
[mode1] datatype1,
datatype1,
parameter2
parameter2 [mode2]
[mode2] datatype2,
datatype2,
.. .. .)]
.)]
RETURN
RETURN datatype
datatype
IS|AS
IS|AS
PL/SQL
PL/SQL Block;
Block;
A Function
create
create or
or replace
replace function
function
rating_message(rating
rating_message(rating IN IN NUMBER)
NUMBER)
return
return VARCHAR2
VARCHAR2
AS NOTE THAT YOU
AS DON'T SPECIFY
BEGIN
BEGIN THE SIZE
IF
IF rating
rating >> 77 THEN
THEN
return
return 'You
'You are
are great';
great';
ELSIF
ELSIF rating
rating >=>= 55 THEN
THEN
return
return 'Not
'Not bad';
bad';
ELSE
ELSE
return
return 'Pretty
'Pretty bad';
bad';
END
END IF;
IF;
END;
END;
//
Calling the function

declare
declare
paulRate:=9;
paulRate:=9;
Begin
Begin
dbms_output.put_line(ratingMessage(paulRate));
dbms_output.put_line(ratingMessage(paulRate));
end;
end;
//

More functions: p4.sql


:Creating a function
create or replace function squareFunc(num in number)
return number
is
BEGIN
return num*num;
End;
/

:Using the function


BEGIN
dbms_output.put_line(squareFunc(3.5));
END;
/
Stored Procedures and Functions
• The procedures and functions we discussed were
called from within the executable section of the
anonymous block.
• It is possible to store the procedure or function
definition in the database and have it invoked from
various of environments.
• This feature allows for sharing of PL/SQL code by
different applications running in different places.
Stored function: p5.sql Call Stored function

SQL>SELECT CNO, CNAME, get_city(cno)


2 from customers;
CNO CNAME GET_CITY(CNO)
------ --------- --------------------
1111 Charles Wichita
2222 Bertram Wichita

get_city function returns city name given customer number.


customers(cno, cname, zip) zipcodes(cnum, zip, city)
Benefits of Stored Procedures I
• Security
– Control data access through procedures and functions.
– E.g. grant users access to a procedure that updates a table,
but not grant them access to the table itself.
• Performance
The information is sent only once between database and
application and thereafter invoked when it is used.
– Network traffic is reduced compared with issuing individual
SQL statements or sending the text of an entire PL/SQL block
– A procedure's compiled form is readily available in the
database, so no compilation is required at execution time.
– The procedure might be cached
Benefits of Procedures II

• Memory Allocation
– Stored procedures take advantage of the shared memory capabilities of
Oracle
– Only a single copy of the procedure needs to be loaded into memory for
execution by multiple users.
• Productivity
– By designing applications around a common set of procedures, you can
avoid redundant coding and increase your productivity.
– Procedures can be written to insert, update, or delete rows from a table
and then called by any application without rewriting the SQL statements
necessary to accomplish these tasks.
– If the methods of data management change, only the procedures need to
be modified, not all of the applications that use the procedures.
Benefits of Procedures III

• Integrity
– Stored procedures improve the integrity and consistency of
your applications. By developing all of your applications
around a common group of procedures, you can reduce the
likelihood of committing coding errors.
– You can test a procedure or function to guarantee that it
returns an accurate result and, once it is verified, reuse it in
any number of applications without testing it again.
– If the data structures referenced by the procedure are
altered in any way, only the procedure needs to be
recompiled; applications that call the procedure do not
necessarily require any modifications.
Procedures VS Functions
• Procedures are traditionally the workhorse of
the coding world
• functions are traditionally the smaller, more
specific pieces of code.
• In general, if you need to update the chart of
accounts, you would write a procedure.
• If you need to retrieve the organization code
for a particular GL account, you would write a
function.
42
Procedures VS Functions(cont..)
Here are a few more differences between a
procedure and a function:
• A function MUST return a value
• A procedure cannot return a value
• Procedures and functions can both return data
in OUT and IN OUT parameters
• The return statement in a function returns
control to the calling program and returns the
results of the function
43
Procedures VS Functions (cont..)
• The return statement of a procedure returns
control to the calling program and cannot return
a value
• Functions can be called from SQL, procedure
cannot
• Functions are considered expressions,
procedure are not
• That's about all the differences I can think of off
the top of my head. Can you think of any more?
44

You might also like