Welcome to our comprehensive guide on PL/SQL Functions! This tutorial is designed to help you understand PL/SQL functions, their importance, and how to use them effectively. Whether you're a beginner or an intermediate learner, we've got you covered!
PL/SQL functions are self-contained blocks of code that return a value when called. They encapsulate logic, making your code more modular, reusable, and easier to maintain.
A PL/SQL function consists of the following parts:
-- Function declaration
CREATE OR REPLACE FUNCTION function_name(parameters)
RETURN datatype
IS
-- Function body
BEGIN
-- Function logic here
RETURN result;
END;
-- Function call
SELECT function_name(arguments) FROM table_name;Let's create a function that calculates the factorial of a number.
-- Function declaration
CREATE OR REPLACE FUNCTION factorial(p_number IN NUMBER)
RETURN NUMBER
IS
v_result NUMBER := 1;
BEGIN
FOR i IN 2 .. p_number LOOP
v_result := v_result * i;
END LOOP;
RETURN v_result;
END;
-- Function call
SELECT factorial(5) FROM dual; -- Output: 120Now, let's create a function that calculates the area of a rectangle with two parameters (length and width).
-- Function declaration
CREATE OR REPLACE FUNCTION area_of_rectangle(p_length IN NUMBER, p_width IN NUMBER)
RETURN NUMBER
IS
v_area NUMBER := p_length * p_width;
BEGIN
RETURN v_area;
END;
-- Function call
SELECT area_of_rectangle(5, 10) FROM dual; -- Output: 50What does a PL/SQL function do?
Stay tuned for more advanced PL/SQL functions, tips, and examples in our upcoming lessons! Happy learning! 🥳