0% found this document useful (0 votes)
7 views

UNIT3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

UNIT3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

UNIT- 3

PL/SQL DATABASE OBJECTS


What is database Object?
• Database objects are defined objects in a database that are used to
store or manipulate data.
• They help users access information in a database more logically.
• Examples of database objects include:
• Tables, Indexes, view, stored procedures and functions, triggers.
 What Are Procedures / Functions
• A procedures or function is logically grouped set of SQL and PL/SQL Statement
that performed a specific tasks.
• A stored procedures or function is a name PL/SQL code block that has been
compiled and stored in one of the oracle engine system tables.
• To make a procedure or function dynamic, you can pass parameters to it before
execution.
• A procedure or function can change its behavior based on the parameters
passed to it.
• Procedures and function are made up of:
A declarative part
An executable part
An optional exception-handling part
Declarative part
• The declarative part may contain the declarations of cursors, constants, variables, exceptions
and subprograms. These objects are local to the procedure or function.
• The objects become invalid once the user exits from the procedure or the function.
Executable Part
• The executable part is a PL/SQL block consisting of SQL and PL/SQL statements that assign
values, control execution and manipulate data.
• The action that the procedure or function is expected to perform is coded here. The data that
is to be returned back to the calling environment is also returned from here.
• The variables declared are put to use within this block
Exception Handling Part
• This part contains code that deals with exceptions that may be raised during the execution of
code in the executable part.
• An Oracle exception handler can be redirected to the exception handling section of the
procedure or function where the procedure or function determines the actual action that must
be carried out by Oracle's exception handler.
 WHERE DO STORED PROCEDURES AND FUNCTIONS RESIDE?
• Procedures and Functions are stored in the Oracle database.
• They can be invoked or called by any PL/SQL block that appears within an application.
• Before a procedure or function is stored, the Oracle engine parses and compiles the procedure
or function.
How Does The Oracle Engine Create A Stored Procedure / Function?
The following steps are performed automatically by the Oracle engine while creating a
procedure:
 Compiles the procedure or function
 Stores the procedure or function in the database
 The Oracle engine compiles the PL/SQL code block. If an error occurs during the compilation of
the procedure or function, an invalid procedure or function gets created.
 The Oracle engine displays a message after creation that the procedure or function was created
with compilation errors.
• compilation process does not display the errors. These errors can be viewed using
the SELECT statement
SELECT * FROM USER_ERRORS
• When a procedure or function is called , THE oracle engine load the complied
procedure or function in a memory area called System Global Area(SGA).
• This allow the code to be executed quickly. Once loaded in SGA other user also
can accesses the same procedure and function if they have been granted
permission to do so.
How Does the Oracle Engine Execute Procedure/Function?
The Oracle engine performs the following steps to execute a procedure or function:
a) Verifies user access
b) Verifies procedure or function validity
c) Executes the procedure or function
• The Oracle engine checks if the user who called the procedure or function has the
execute privilege for the procedure or function.
• If the user is invalid, then access is denied otherwise the Oracle engine proceeds to
check whether the called procedure or function is valid or not.
• The status of a procedure or function is shown by the use of a SELECT as follow.
• SELECT <ObjectName>, <ObjectType>, <Status> FROM <UserObjects> WHERE
<ObjectType> = <'PROCEDURE’>
OR
• SELECT <Object_Name>, <Object_Type>, <Status> FROM <User_Objects>
WHERE <Object_Type> = <'FUNCTION’ >
example : SELECT object_name, object_type, status
FROM user_objects
WHERE object_type = 'PROCEDURE';

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.

PROCEDURES Is the name of the procedure to be created.


ARGUMENT Is the name of an argument to the procedure. Parentheses can be omitted if no arguments are
present.

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

Passed to a procedure or function by the caller


Defined and used only within the program block

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;

- The procedure can also be called from another PL/SQL block


BEGIN
greetings;
END;
/
• Deleting a Procedure
• A standalone procedure is deleted with the DROP PROCEDURE
statement.
• Syntax for deleting a procedure is −
DROP PROCEDURE procedure-name;

• You can drop the greetings procedure by using the following


statement −
DROP PROCEDURE greetings;
CREATE OR REPLACE PROCEDURE double_value(
input_number IN NUMBER -- Input parameter
) AS
BEGIN
-- Directly output the doubled value
DBMS_OUTPUT.PUT_LINE('Doubled value is ' || (input_number * 2));
END double_value;
/
BEGIN
-- Call the stored procedure with an input number
double_value(5);
END;
/
CREATE OR REPLACE PROCEDURE double_value(
input_number IN NUMBER, -- Input parameter
output_number OUT NUMBER -- Output parameter
) AS
BEGIN
-- Calculate and store the doubled value in the output parameter
output_number := input_number * 2;
DBMS_OUTPUT.PUT_LINE('Doubled value is ' || output_number);
END;
/
DECLARE
output_num NUMBER;
BEGIN
-- Call the stored procedure with an input number
double_value(5, output_num);
END;
/
CREATE OR REPLACE PROCEDURE check_number(
input_number IN NUMBER -- Input parameter
) AS
BEGIN
IF input_number > 0 THEN
DBMS_OUTPUT.PUT_LINE(input_number || ' is positive.');
ELSIF input_number < 0 THEN
DBMS_OUTPUT.PUT_LINE(input_number || ' is negative.');
ELSE
DBMS_OUTPUT.PUT_LINE(input_number || ' is zero.');
END IF;
END;
/
BEGIN
-- Call the stored procedure with a number
check_number(-3);
END;
/
CREATE OR REPLACE PROCEDURE check_range(
input_number IN NUMBER -- Input parameter
) AS
BEGIN
IF input_number BETWEEN 1 AND 10 THEN
DBMS_OUTPUT.PUT_LINE(input_number || ' is within the range of 1 to 10.');
ELSE
DBMS_OUTPUT.PUT_LINE(input_number || ' is outside the range of 1 to 10.');
END IF;
END;
/
BEGIN
-- Call the stored procedure with a number
check_range(7);
END;
/
CREATE OR REPLACE PROCEDURE double_value(
input_output_number IN OUT NUMBER -- IN OUT parameter
) AS
BEGIN
-- Calculate and store the doubled value in the IN OUT parameter
input_output_number := input_output_number * 2;
DBMS_OUTPUT.PUT_LINE('Doubled value is ' || input_output_number);
END;
/
DECLARE
input_output_num NUMBER := &m; -- Initial value for the IN OUT parameter
BEGIN
-- Call the stored procedure with an IN OUT parameter
double_value(input_output_num);

-- 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;

-- Check if the record was deleted


IF SQL%ROWCOUNT = 0 THEN
DBMS_OUTPUT.PUT_LINE('No employee found with ID ' || p_emp_id);
ELSE
-- Commit the transaction
COMMIT;
DBMS_OUTPUT.PUT_LINE('Employee deleted successfully!');
END IF;

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;

-- Display the employee details


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || p_emp_id);
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_emp_name);
DBMS_OUTPUT.PUT_LINE('Employee Salary: ' || v_emp_salary);
DBMS_OUTPUT.PUT_LINE('Employee Department: ' || v_emp_dept);

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.

FUNCTION Is the name of the function to be created.


ARGUMENT Is the name of an argument to the function. Parentheses can be omitted if no
arguments are present.

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.

PL/SQL Is the definition of procedure consisting of PL/SQL statements.


subprogram body
Function: In PL/SQL, functions don’t use IN OUT parameters like procedures.
It use IN parameters to pass values and return values via the function’s return type.
A function returns a single value using the return statement instead of using IN OUT.

CREATE OR REPLACE FUNCTION greetings


RETURN VARCHAR2 -- Return type
AS
BEGIN
-- Return the greeting message
RETURN 'Hello, World!';
END;
/
You can use a SELECT statement to call the function directly
Method 1: SELECT greetingd() FROM dual;
You can also call the function using PL/SQL block of code
Method 2:
begin
variable := function_name(parameter1, parameter2, ...);
End;
/
CREATE OR REPLACE FUNCTION add_numbers (
p_num1 IN NUMBER,
p_num2 IN NUMBER
) RETURN NUMBER
IS
BEGIN
RETURN p_num1 + p_num2;
END;
/
DECLARE
v_sum NUMBER; -- Declare a variable to store the result
BEGIN
-- Call the function and store the result in v_sum
v_sum := add_numbers(10, 20);
-- Output the result
DBMS_OUTPUT.PUT_LINE('The sum is: ' || v_sum);
END;
• Steps to Call a Function:
Declare a variable to store the result.
Call the function and assign the returned value to the variable.
Use the returned value as needed in the program.
CREATE OR REPLACE FUNCTION square_number (num IN number)
RETURN NUMBER
IS
Result number;
BEGIN
result:= num *num;
RETURN result;
END;
/
DECLARE
sq_value NUMBER; -- Declare a variable to store the result
BEGIN
-- Call the function and store the result in v_sum
sq_value := square_number(5);
-- Output the result
DBMS_OUTPUT.PUT_LINE(‘Number is ' || sq_value);
END;
/
Example1: write a PL/SQL block for function to
calculate bonus based on salary
create or replace function bonus
(p_salary number)
return number
IS
v_bonus number;
begin
v_bonus:=p_salary*0.1;
return v_bonus;
end;
/
Call function:

select employee_id,salary,bonus(salary)As bonus from emp;


example of a PL/SQL function that calculates the bonus, but
the bonus percentage depends on different salary ranges.
CREATE OR REPLACE FUNCTION calculate_bonus (p_salary IN NUMBER)
RETURN NUMBER
IS
v_bonus NUMBER; -- Variable to store the calculated bonus
BEGIN
-- Calculate bonus based on different salary ranges
IF p_salary < 30000 THEN
v_bonus := p_salary * 0.05; -- 5% bonus for salary less than 30,000

ELSIF p_salary BETWEEN 30000 AND 60000 THEN


v_bonus := p_salary * 0.10; -- 10% bonus for salary between 30,000 and 60,000
ELSE
v_bonus := p_salary * 0.20; -- 20% bonus for salary greater than 60,000
END IF;

RETURN v_bonus; -- Return the calculated bonus


END;
/
DECLARE
v_salary NUMBER := &ENTER_SALARY; -- Example salary
v_bonus NUMB ER; -- Variable to hold the bonus
BEGIN
-- Call the function and assign the result to v_bonus
v_bonus := calculate_bonus(v_salary);

-- Display the bonus


DBMS_OUTPUT.PUT_LINE('The bonus for the salary ' || v_salary || '
is: ' || v_bonus);
END;
/
Function Procedure
A function is a block of code that performs a specific task A procedure is a block of code that performs a specific task
and returns a value. but does not return a value.
Function return a value using a RETURN keyword. you can use OUT parameters to return values indirectly.
Must return a single value using the RETURN keyword. Can return multiple values via OUT parameters.
It can be called directly from a SQL statements like SELECT. Cannot be called directly from a SQL statement.
Used mainly to calculations and return a value. Used to perform a DML operation without returning a value
directly.
Best for simple operations Best for complex operations.
CREATE OR REPLACE FUNCTION function_name CREATE OR REPLACE PROCEDURE procedure_name
(parameter_name INdatatype, ...) (parameter_name datatype, ...)
RETURN return_datatype IS
IS BEGIN
BEGIN -- SQL AND PL/SQL STATEMENTS;
-- SQL AND PL/SQL STATEMENTS; END;
RETURN value;
END;
Syntax: to call function directly Syntax: to call procedure
variable := function_name(args); EXECUTE procedure_name(args);
ADVANTAGES OF USING A PROCEDURE OR FUNCTION
1. Security - Stored procedures and functions help improve security by controlling
who can access and change important data. This ensures that only certain
people can see or update sensitive information and it also helps maintain data
accuracy
example: GRANT EXECUTE ON my_procedure TO john_doe;
REVOKE EXECUTE ON my_procedure FROM user_name;
2. Performance - It improves database performance by:
a. Sending less data over the network.
b. they don't need to be compiled each time.
c. Reducing disk I/O use, as they are kept in memory for quick access.
3. Memory Allocation - The amount of memory used decreases because stored
procedures or functions can share memory.
Only one copy of procedure needs to be loaded for execution by multiple users.
Once a copy of a procedure or function is loaded into the Oracle engine's memory, other
users with permission can access and use it.
4 Productivity : Writing procedures and functions helps avoid repeating the same
code, which saves time and increases productivity.
5 Integrity :
Once a procedure or function is compiled and stored in the database with a valid
status, it means it works correctly and doesn't need to be tested again.
Since it's stored in the Oracle engine, they are protected and managed by the
engine’s security, ensuring their accuracy and integrity.
ERROR HANDLING IN PL/SQL
• Each SQL statement is executed by the Oracle Engine.
• The oracle engine will execute every SQL sentences within PL/SQL block.
• During execution, errors can happen for various reasons, such as data issues,
constraints, or incorrect queries.
• An error occurs during the program execution is called Exception in PL/SQL.
OR
In PL/SQL, an error condition is called an exception.
• When an SQL sentence fails the oracle engine is the first to recognize this as an
Exception condition.
• When an error occurs, an exception is raised.
• The Oracle engine immediately tries to handle the exception condition and
resolve it.
• This is done by raising a built-in exception handler.
• An exception handler is a code block in memory that will attempt to resolve
the current exception condition.
• The oracle engine can recognize every exception condition that occurs in
memory.
• The oracle engine has about 15 to 20 named exception handlers.
• These exception handler identified by not name but 4 integer preceded by
hyphen.Ex. -1414
• Syntax:
EXCEPTION
WHEN exception_name THEN
user defined action to be carried out
• In PL/SQL, there are two main types of exception handlers used to manage
errors:
1. Predefined Exception Handlers
2. User-defined Exception Handlers
Exception handling and the oracle engine

CLIENT MACHINE SQL sentence within the


SERVER MACHINE
PL/SQL block passed to the
Oracle engine and some SQL
PL/SQL BLOCK statement fails
ORACLE ENGINE
OF CODE
NETWORK

The Oracle Engine recognizes


the error and raises an
appropriate exception Oracle Engine’s
handler which scans the HDD with
PL/SQL block to see if user user data
defined exception handling
code exists.
1. ORACLE’S NAMED XCEPTION HANDLERS
• The Oracle engine has a set of pre-defined oracle error handlers called
named exceptions.
• These error handlers are referenced by their name.
• The following are some of the pre-defined oracle named exception handlers.
1. DUP_VAL_ON_INDEX: Raised when an insert and update operation tries to
add duplicate values in a column that has a unique constraint.
2. LOGIN_DENIED: Raised when an invalid username/password was used to
log onto oracle.
3. NO_DATA_FOUND: Raised when a select statement returns zero or rows.
4. NOT_LOGGED_ON: Raised when PL/SQL issues an oracle call without being
logged onto oracle.
5. PROGRAM_ERROR: Raised when PL/SQL has an internal problem.
6. TIMEOUT_ON_RESOURCE: Raised when oracle waits too long to access a
resource beyond the user-defined limit.
7. TOO_MANY_ROWS: Raised when a select statement returns more than one
row.
8. VALUE_ERROR: Raised when the data type or data size is invalid.
9. OTHER: stands for all other exceptions not explicitly named.
DECLARE -- <declarations section>
BEGIN --<executable command(s)>
EXCEPTION --<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements

WHEN exception2 THEN


exception2-handling-statements

WHEN exception3 THEN


exception3-handling-statements

WHEN others THEN


exception3-handling-statements
END;
Example of NO_DATA_FOUND
create table student(s_id number , DECLARE
s_name varchar(20),marks number);
V_sname student.s_name%type;
insert into student values(1, 'Suraj',100); BEGIN
SELECT s_name into v_sname from student
insert into student values(2,'Praveen',97); where s_id=4';
dbms_output.put_line(v_sname);
insert into student values(3, 'Jessie', 99); exception
WHEN no_data_found THEN
select * from student; dbms_output.put_line('ERROR');
dbms_output.put_line('there is no student');
end;
Example of TOO_MANY_ROWS
DECLARE
temp varchar(20);

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.

• What is business rules?


• A business rule is a simple rule or instruction that tells how things should work in a
business.
OR
• A business rule is a clear rule that tells people what to do in a business.
• In a commercial application, when data is changed or added, it needs to be
checked to make sure it follows the business rules.
• Simple Example of business rules:
• If a new order is made, the system checks if the customer has enough money.
• If someone applies for a job, the system checks if they are 18 or older.
• A salesperson must meet their target to earn a commission.

• 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

SELECT salesman_no, rate_of_commission, tgt_to_get, ytd_sales INTO sman_no,


comm_rate, tgt_sales, act_sales FROM salesman_master WHERE
salesman_no=&sman_no;
IF act_sales < tgt_sales THEN
RAISE less_than_target;
ELSE
INSERT INTO commission_payable VALUES (sman_no, sysdate, act_sales *
comm_rate/100);

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.

You might also like