M BARATH RAJ-22IT012
Ex No : 9 Procedures, Functions and packages in PL/SQL
Date :
Aim:
To execute the functions, procedures and Packages in SQL
Description
Functions:
A function is a named PL/SQL Block which is similar to a procedure. The major
difference
between a procedure and a function is, a function must always return a value, but a
procedure
may or may not return a value.
SYNTAX
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
M BARATH RAJ-22IT012
Application :
To calculate the shipping cost based on the provided weight and distance values.
CREATE OR REPLACE FUNCTION calculate_shipping_cost (
weight_in_kg IN NUMBER,
distance_in_km IN NUMBER
) RETURN NUMBER
IS
base_rate_per_kg CONSTANT NUMBER := 5;
rate_per_km CONSTANT NUMBER := 2;
total_cost NUMBER;
BEGIN
total_cost := (weight_in_kg * base_rate_per_kg) + (distance_in_km *
rate_per_km);
RETURN total_cost;
END calculate_shipping_cost;
/
M BARATH RAJ-22IT012
RESULT :
Procedures :
A procedure is a group of PL/SQL statements that you can call by name.
A procedure is a module performing one or more actions , it does not
need to return any values.
Creating a Procedure:
Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END
procedure_name;
APPLICATION ;
TO UPDATE SAVNIGS :
CREATE OR REPLACE PROCEDURE update_savings(
p_increase_amount IN NUMBER
)
IS
v_total_rows NUMBER;
BEGIN
UPDATE cost_ledger
SET savings = savings + p_increase_amount;
M BARATH RAJ-22IT012
v_total_rows := SQL%ROWCOUNT;
IF v_total_rows = 0 THEN
dbms_output.put_line('No records updated.');
ELSE
dbms_output.put_line(v_total_rows || ' records updated.');
END IF;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('An error occurred: ' || SQLERRM);
END update_savings;
/
OUTPUT :
M BARATH RAJ-22IT012
PACKAGES:
Packages are schema objects that groups logically related PL/SQL types,
variables, and subprograms.
A package will have two mandatory parts −
Package specification
Package body or definition .
SYNTAX:
For creating package:
CREATE [OR REPLACE] PACKAGE <package_name>
IS
<sub_program and public element declaration>
.
.
END <package name>
For creating package body:
CREATE [OR REPLACE] PACKAGE BODY <package_name>
IS
<global_declaration part>
<Private element definition>
<sub_program and public element definition>
.
<Package Initialization>
END <package_name>
M BARATH RAJ-22IT012
APPLICATION :
M BARATH RAJ-22IT012
Result:
Thus the functions , procedures and packages are successfully executed in SQL.