Here are the answers to each question, formatted to fit on separate A4 pages. Each answer is concise and includes examples where applicable.
Page 1: Advantages of Using Functions in PL/SQL
Using functions in PL/SQL offers several key advantages:
- Modularity: Functions allow you to break down complex tasks into smaller, manageable units, making code easier to develop and maintain.
- Reusability: Once defined, functions can be called multiple times from different parts of a program, reducing redundancy and promoting code reuse.
- Readability: By encapsulating logic within functions, code becomes more organized and easier to understand, enhancing readability.
- Abstraction: Functions hide complex implementation details, allowing developers to focus on higher-level logic and improving code clarity.
- Ease of Testing: Individual functions can be tested independently, simplifying the debugging and validation process.
- Performance Optimization: Frequently used operations can be optimized within functions, improving overall application performance.
- Parameterization: Functions accept parameters, enabling dynamic behavior and flexibility in their usage.
These advantages collectively contribute to more efficient, scalable, and maintainable PL/SQL code.
Page 2: PL/SQL Function to Return Total Salary Paid to a Department
-- Table Structure
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
name VARCHAR2(100),
salary NUMBER,
department_id NUMBER
);
-- Sample Data
INSERT INTO employees VALUES (1, 'John Doe', 5000, 10);
INSERT INTO employees VALUES (2, 'Jane Smith', 6000, 10);
INSERT INTO employees VALUES (3, 'Alice Johnson', 7000, 20);
-- Function to Calculate Total Salary by Department
CREATE OR REPLACE FUNCTION get_dept_total_salary(p_dept_id NUMBER) RETURN NUMBER IS
v_total_salary NUMBER := 0;
BEGIN
SELECT SUM(salary) INTO v_total_salary
FROM employees
WHERE department_id = p_dept_id;
RETURN v_total_salary;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 0;
END;
Usage Example:
SELECT get_dept_total_salary(10) FROM dual; -- Returns 11000
Page 3: PL/SQL Function to Return Full Name of an Employee
-- Function to Retrieve Employee Full Name
CREATE OR REPLACE FUNCTION get_employee_name(p_emp_id NUMBER) RETURN VARCHAR2 IS
v_full_name VARCHAR2(100);
BEGIN
SELECT name INTO v_full_name
FROM employees
WHERE employee_id = p_emp_id;
RETURN v_full_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 'Employee not found';
END;