Functions
Functions
Functions
S.Naji
Functions and procedures
Procedures and functions that are created outside
of a package are called stored or standalone
subprograms.
Procedures and functions defined within a package
are known as packaged subprograms.
Procedures and functions nested inside other
subprograms or within a PL/SQL block are known
as local subprograms, which cannot be referenced
by other applications and exist only inside of the
enclosing block
Function Declaration
CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [function_name];
Functions Vs Procedures
Procedure may return none or more values.Function must always return one value
either a scalar value or a table.
DBMS_OUTPUT.PUT_LINE(factorial(10));
END;
/
Create Table for function operation
create table Employee(
ID VARCHAR2(4 BYTE) NOT NULL,
First_Name VARCHAR2(10 BYTE),
Last_Name VARCHAR2(10 BYTE),
Start_Date DATE,
End_Date DATE,
Salary Number(8,2),
City VARCHAR2(10 BYTE),
Description VARCHAR2(15 BYTE)
)
/
Insert Rows
insert into Employee(ID, First_Name,
Last_Name, Start_Date,
End_Date, Salary, City, Description)
values ('01','Jason', 'Martin',
to_date('19960725','YYYYMMDD'),
to_date('20060725','YYYYMMDD'), 1234.56,
'Toronto', 'Programmer')
/
Example
CREATE FUNCTION average_salary RETURN
NUMBER AS
v_average_salary NUMBER;
BEGIN
SELECT AVG(salary)
INTO v_average_salary
FROM employee;
RETURN v_average_salary;
END;
/
Calling the Function
describe emp_count;
Example
create or replace
function getArea (i_rad NUMBER)
return NUMBER
is
v_pi NUMBER:=3.14;
begin
return v_pi * (i_rad ** 2);
end;
/
Calling the function