Real-World Examples
1. Data Validation Using Triggers
Triggers are ideal for enforcing business rules and validating data before it's inserted or updated in the database.
Scenario:
Ensure that no employee is inserted into the employees
table with a salary less than 10,000.
Code Example:
Explanation:
- This
BEFORE
trigger checks the salary value before anINSERT
orUPDATE
operation. - If the salary is less than 10,000, it raises a custom error message.
2. Generating Reports Using Cursors
Cursors can be used to fetch and process multiple rows of data for generating detailed reports.
Scenario:
Generate a report of employees with their names and salaries who earn more than 50,000.
Code Example:
Explanation:
- The cursor
emp_cursor
fetches employees with salaries greater than 50,000. - The
DBMS_OUTPUT.PUT_LINE
is used to print the report.
3. Automating Business Logic with Procedures
Procedures allow encapsulating business rules and automating tasks.
Scenario:
Automate the process of giving a 10% bonus to all employees in a specific department.
Code Example:
Execution:
Explanation:
- The procedure
give_bonus
updates the salary of employees in the specified department. - It includes exception handling for errors during the update.
4. Exception Handling in Real-Life Scenarios
Robust error handling ensures smooth operation in unexpected situations.
Scenario:
Handle errors gracefully during a fund transfer between two accounts.
Code Example:
Execution:
Explanation:
- Validates balance and performs the fund transfer.
- Handles specific (
NO_DATA_FOUND
) and general (WHEN OTHERS
) exceptions.
5. Implementing a Simple Inventory Management System
PL/SQL can be used to implement systems like inventory management for tracking stock levels.
Scenario:
Track stock levels and alert if stock for any item falls below the minimum threshold.
Step 1: Create the Tables
Step 2: Insert Sample Data
Step 3: Create a Procedure to Restock
Step 4: Create a Trigger to Check Stock Levels
Execution:
Explanation:
- The
restock_item
procedure adds stock for an item. - The
trg_check_stock
trigger alerts if the stock falls below the minimum level.
Summary of Scenarios
Scenario | Purpose |
---|---|
Data Validation Using Triggers | Enforce business rules before data is inserted or updated. |
Generating Reports Using Cursors | Fetch and process data for detailed reports. |
Automating Business Logic | Automate repetitive tasks like applying bonuses. |
Exception Handling | Handle errors in real-world operations like fund transfers. |
Inventory Management System | Track and manage stock levels with alerts for low stock. |
These scenarios demonstrate the practical use of PL/SQL for implementing real-world business logic, data processing, and error handling effectively.
Leave a Comment