Unlocking the World of Business Intelligence with SQLBI

What is PL/SQL?
PL/SQL is Oracle's procedural extension to SQL. It allows
you to write code that includes both SQL statements and procedural constructs
such as loops, conditions, and error handling.
What are Procedures and Functions?
Functions are similar to procedures but are designed to return a single value. They are often used for calculations or processing data and can be called directly within SQL statements.
Advantages
Advantages of Using Procedures and Functions
Syntax and Examples
Procedure Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name (parameter_list)
IS
BEGIN
-- SQL and PL/SQL statements
END procedure_name;
/
Normal Example:
Imagine you want to add a new employee to an "employees" table. The procedure would look like this:
CREATE OR REPLACE PROCEDURE add_employee (
p_emp_id IN NUMBER,
p_name IN VARCHAR2,
p_salary IN NUMBER
)
IS
BEGIN
INSERT INTO employees (emp_id, name, salary)
VALUES (p_emp_id, p_name, p_salary);
COMMIT;
END add_employee;
/
Real-Time Example:
In a payroll system, an administrator may use a procedure to
add employee records after collecting data from various sources. This reduces
manual errors and speeds up the data entry process.
Function Syntax
Basic Syntax:
CREATE [OR REPLACE] FUNCTION function_name (parameter_list)
RETURN return_datatype
IS
BEGIN
-- SQL and PL/SQL statements
RETURN value;
END function_name;
/
Normal Example:
Suppose you need to calculate the annual salary from a monthly salary. The function would look like this:
CREATE OR REPLACE FUNCTION calculate_annual_salary (
p_monthly_salary IN NUMBER
)
RETURN NUMBER
IS
BEGIN
RETURN p_monthly_salary * 12;
END calculate_annual_salary;
/
Real-Time Example:
In a business application, the function calculate_annual_salary
can be used within SQL queries to dynamically compute annual salaries from
stored monthly salary data. For instance:
SELECT emp_id, name, salary, calculate_annual_salary(salary) AS annual_salary
FROM employees;
Key Points to Remember
Summary
Comments
Post a Comment