UNIT3
UNIT3
Only if the status is valid, will a procedure or function be executed. Once found valid, the
Oracle engine then loads a procedure or function into memory (i.e. if it is not currently
present in memory) and executes it.
Syntax of Creating Stored Procedures
• CREATE OR REPLACE PROCEDURE procedure_name
(parameter1 IN datatype1, parameter2 OUT datatype2, parameter3 IN OUT datatype3)
AS/IS
-- Declaration section: declare local variables
variable1 datatype1;
variable2 datatype2;
BEGIN
-- PL/SQL code block
-- Body of the procedure
-- SQL statements, control structures, etc.
EXCEPTION
-- Exception handling section -- Handle exceptions if any
END procedure_name;
/
Keywords And Parameters of Procedure
REPLACE Recreates the procedure if it already exists. This option is used to change the definition of an
existing procedure without dropping, recreating and re-granting object privileges previously
granted on it. If a procedure is redefined the Oracle engine recompiles it
SCHEMA Is the schema to contain the procedure. The Oracle engine takes the default schema to be the
current schema, if it is omitted.
IN Indicates that the parameter will accept a value from the user.
OUT Indicates that the parameter will return a value to the user.
IN OUT Indicates that the parameter will either accept a value from the user or return a value to the
user.
DATA TYPE Is the data type of an argument. It supports any data type supported by PL/SQL.
PL/SQL Is the definition of procedure consisting of PL/SQL statements.
subprogram body
Variable Parameter
A variable is a storage location in memory used to hold a A parameter is a special kind of variable that is passed into a
value. procedure, function
Used to store and manipulate data within a program Used to pass values into or out of a procedure, function, or
subroutine
Must be explicitly initialized within the block Values are provided when the procedure/function is called
Can be modified within the block after initialization IN parameters cannot be modified; OUT and IN OUT
parameters can be modified
Syntax: Syntax:
Variable1 datatype(size); Parameter1 IN datatype;
Example : Example:
v_emp_id NUMBER; p_emp_id IN NUMBER
CREATE OR REPLACE PROCEDURE greetings
IS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
- The above procedure named 'greetings' can be called with the EXECUTE
keyword as −
EXECUTE greetings;
-- Display the result after the procedure has modified the parameter
DBMS_OUTPUT.PUT_LINE('The value after doubling is ' || input_output_num);
END;
/
CREATE OR REPLACE PROCEDURE add_employee (
p_emp_id IN NUMBER, -- No size mentioned
p_emp_name IN VARCHAR2 -- No size mentioned
)
IS
BEGIN
-- Procedure logic
INSERT INTO EMP (emp_id, emp_name)
VALUES (p_emp_id, p_emp_name);
END;
/
BEGIN
update_employee(101, 'John Smith', 60000, 'HR');
END;
/
CREATE OR REPLACE PROCEDURE delete_employee (
p_emp_id IN EMP.emp_id%TYPE
) IS
BEGIN
-- Delete the employee from the EMP table
DELETE FROM EMP
WHERE emp_id = p_emp_id;
END;
/
• BEGIN
• delete_employee(101);
• END;
•/
CREATE OR REPLACE PROCEDURE select_employee (
p_emp_id IN EMP.emp_id%TYPE
) IS
v_emp_name EMP.emp_name%TYPE;
v_emp_salary EMP.emp_salary%TYPE;
v_emp_dept EMP.emp_dept%TYPE;
BEGIN
-- Select employee details from the EMP table
SELECT emp_name, emp_salary, emp_dept
INTO v_emp_name, v_emp_salary, v_emp_dept
FROM EMP
WHERE emp_id = p_emp_id;
END;
/
• BEGIN
• select_employee(101);
• END;
•/
Syntax of CREATING A FUNCTIONS
• CREATE OR REPLACE FUNCTION function_name
(parameter1 IN datatype1, parameter2 IN datatype2)
RETURN return_datatype
IS
-- Declaration section: declare local variables
variable1 datatype1;
variable2 datatype2;
BEGIN
-- PL/SQL code block
-- Body of the procedure
-- SQL statements, control structures, etc.
RETURN return_value;
EXCEPTION
-- Exception handling section -- Handle exceptions if any
END;
/
Keywords And Parameters Of Function
REPLACE Recreates the function if it already exists. This option is used to change the definition
of an existing function without dropping, recreating and re-granting object privileges
previously granted on it. If a function is redefined, Oracle engine recompiles it.
SCHEMA Is the schema to contain the function. The Oracle engine takes the default schema to
be the current schema, if it is omitted.
IN Indicates that the parameter will accept a value from the user.
RETURN data type Is the data type of the function’s return value. Because every function must return a
value, this clause is required. It support any data type supported by PL/SQL.
BEGIN
SELECT s_name into temp from student;
dbms_output.put_line(temp);
EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('error trying to fetch too many rows');
end;
DECLARE
v_emp_id employees.emp_id%TYPE := 1001;
BEGIN
-- Attempt to update the emp_name column to a value that violates the unique constraint
UPDATE employees
SET emp_name = 'John Doe' -- Assume 'John Doe' already exists in another row
WHERE emp_id = v_emp_id;
DBMS_OUTPUT.PUT_LINE('Update Successful');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Error: Duplicate value for employee name.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Unexpected error: ' || SQLERRM);
END;
/
USER-NAMED EXCEPTION HANDLERS
• user-defined exception handlers allow you to create custom exceptions
that you can raise and handle in your code.
• The Technique that is used to bind a numbered exception handlers (specific
oracle error code)to a name exception using PRAGMA EXCEPTION_INIT().
OR
• PRAGMA EXCEPTION_INIT is used to bind a specific Oracle error code to a
named exception.
• And use these names in the exception section of PL/SQL block.
• This is done in the declare section of the PL/SQL.
DECLARE
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(EXCEPTION_NAME, ERROR_CODE_NO);
• The Pragma action word is a call to a pre-complier , which immediately binds
the numbered exception handler to a name when processed.
• The function Exception_init() take two parameter the first is the user-defined
exception name and the second is the oracle engine’s exception number.
DECLARE
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(exception_name , -60);
BEGIN
PL/SQL STATEMENTS;
EXCEPTION
WHEN exception_name THEN
dbms_output.put_line(‘’); -- handle the error
END;
How to use User-Defined Exception Handlers in PL/SQL (For I/O Validation)
• In PL/SQL, user-defined exception handlers allow you to create custom
exceptions that you can raise and handle in your code.
• This is useful when you want to handle specific conditions (e.g., invalid input
or out-of-range values) that are not covered by Oracle's predefined
exceptions.
• When to Use User-Defined Exceptions
• User-defined exceptions are helpful in scenarios where:
• You want to handle custom error conditions.
• You need to validate user input (I/O validation).
• When you want to use certain logical conditions (e.g., invalid input, out-of-
range values, etc.).
User Defined Exception Handlers (For I/O validation)
• The manner of defining and handling an exception in a pl/sql block of code is
shown in the following example.
EXAMPLE
Two client machines A & B are accessing the same client_master table using
identical PL/SQL code block for updating the bal_due column of the table
client_master.
Client_no Bal_due
C0001 1000
C0002 2000
C0003 2500
C0004 4000
Declare
bal_amt number(10,2);
trans_amt number(10,2);
cl_no varchar(6);
trans_type varchar(1);
resource_busy exception;
PRAGMA EXECPTION_INIT(resource_busy , -00054);
BEGIN
trans_amt:=& trans_amt;
cl_no:=&cl_no;
trans_type:=‘&trans_type’;
select bal_due into bal_amt from client_master where client_no=cl_no FOR UPDATE NOWAIT;
IF trans_type=‘d’ then
update client_master set bal_due = bal_due - trans_amt;
ELSIF trans_type=‘c’ then
update client_master set bal_due = bal_due + trans_amt;
END IF;
EXCEPTION
WHEN resource_busy then
DBMS_OUTPUT.PUT_LINE(‘The row is in use’);
END;
Observation:
The Oracle engine instead of displaying its own error message, will now display a
user-defined message as defined in the exception handling section of the PL/SQL
block of code
EXCEPTION
WHEN RESOURCE_BUSY THEN
DBMS_OUTPUT.PUT_LINE('The row is in use’);
In case the above, error condition was not handled by the user in the exception
section then the Oracle engine will raise it's own error handler and display the
following message to the user:
DECLARE
*
ERROR at line 1:
ORA-00054: resource busy and acquire
with NOWAIT specified
ORA-06512: at line 10
Question: PL/SQL code block that validates a user's age and handles
exceptions using user-defined exceptions for input validation.
DECLARE
-- Declare variables
user_age NUMBER;
is_valid_age BOOLEAN;
BEGIN
-- Simulate user input (in real scenarios, this could be taken from a user
interface or procedure input)
user_age := 45; -- Assume user input is 150, which is not valid
-- Perform input validation (age must be between 18 and 40)
is_valid_age := (user_age >= 18 AND user_age <= 40);
-- Handle the validation result
IF is_valid_age THEN
DBMS_OUTPUT.PUT_LINE('Valid age: ' || user_age);
ELSE
DBMS_OUTPUT.PUT_LINE('Error: Age is out of valid range (1-120). You
entered: ' || user_age);
END IF;
EXCEPTION
-- Generic handler for unexpected errors
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' || SQLERRM);
END;
/
USER DEFINED EXCEPTION HANDLER (FOR
BUSINESS RULE VALIDATION)
• In PL/SQL, user-defined exception handlers allow you to create custom exceptions
that you can raise and handle in your code.
• Steps to create a exception
• Declaration: declare a user-defined exception in the DECLARE section.
• Raising the Exception: You can raise the exception using the RAISE statement when
a specific condition occurs.
• Handling the Exception: In the EXCEPTION section, you write code to handle
(action) the user-defined exception when it is raised.
• If the data violates(breaks) a business rule, the entire record must be rejected.
• Without using user-defined exceptions for business rules, an SQL statement
can run successfully.
• and wrong data might still get inserted into the table because Oracle won’t
detect business rule violations(breaks).
• To catch these errors, user-defined exceptions are used to check specific
conditions and handle business violations(breaks).
Syntax for user define exception for business rules validations
DECLARE
exception_name EXCEPTION;
BEGIN
IF <condition> THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
Question: Write a PL/SQL code block that checks whether a user has sufficient balance and raises
an exception for business validation if the balance is insufficient.
Business rules: minimum balance =1000
DECLARE
-- Declare a user-defined exception
insufficient_funds EXCEPTION;
account_balance NUMBER := 100; -- Example balance
BEGIN
-- Condition to check for insufficient funds
IF account_balance < 200 THEN
RAISE insufficient_funds; -- Raise the custom exception
END IF;
DBMS_OUTPUT.PUT_LINE('Transaction successful.');
EXCEPTION
WHEN insufficient_funds THEN
DBMS_OUTPUT.PUT_LINE('Error: Insufficient funds for this transaction.');
END;
Table Name: Salesman master
Definition :The salesman master Salesmanno Salesman Rateof Tgt To Get Ytd Sales
name Commissio
table records the salesman_no, n
salesman_name, ytd_sales, S00001 Kiran 5 100 50
rate_of_commission along with the S00002 Manish 4 200 300
minimum tgt_to_get.
S00003 Ravi 3 200 350
S00004 Ashish 7 200 150
A salesman is eligible for
commission only when a salesman
achieves the target sales.
Table Name : commission_payable
When commission in paid the
commission amount along with the Salesman_no Date_ofpayment Commision_amount
salesman_no and the
date_of_payment is recorded in
commission _payable table.
Declare
less_than_target Exception;
sman_no salesman_master.salesman_no%type;
tgt_sales salesman_master.tgt_to_get%type;
act_sales salesman_master.ytd_sales%type;
comm_rate salesman_master.rate_of_commission%type;
Begin
IF END;
EXCEPTION
WHEN less_than_target THEN
DBMS_OUTPUT.PUT_LINE ('Salesman No || sman_no || ' is not entitled to get
commission’);
END ;
USER DEFINE EXCEPTION WITH RAISE DBMS_OUTPUT FOR IF AND ELSE CONDITION
DBMS_OUTPUT is used for displaying messages rather than
User-defined exceptions are used for error handling. handling errors.
You can use the RAISE statement to raise the exception, You can use DBMS_OUTPUT.PUT_LINE to print messages based on
when a certain condition is occurs. conditions.
Control moves to the exception handler when raised and it The program keeps running even after displaying messages,
will stop the execution of code. without interrupting or changing the execution path.