Welcome to our PL/SQL Blocks tutorial! In this lesson, we'll dive into the world of PL/SQL, a procedural language used in Oracle databases to manipulate and manage data. By the end, you'll be ready to write your own PL/SQL procedures and functions! 💡
<a name="introduction"></a>
Before we jump in, let's understand why PL/SQL is essential. It enables developers to:
<a name="syntax"></a>
A PL/SQL script is a collection of SQL statements, declarative variables, and control structures enclosed within a BEGIN and END block.
BEGIN
-- PL/SQL code here
END;<a name="variables"></a>
Variables in PL/SQL store data values. We have different data types like:
DECLARE
v_name Char(20) := 'John Doe';
v_age Number(2) := 30;
v_date Date := TO_DATE('2022-01-01', 'YYYY-MM-DD');
BEGIN
-- Use variables in your PL/SQL code
END;<a name="control"></a>
Control structures in PL/SQL allow for conditional and looping logic.
DECLARE
v_age Number(2);
v_status VarChar2(20);
BEGIN
v_age := 18;
IF v_age >= 18 THEN
v_status := 'Eligible to vote';
ELSE
v_status := 'Not eligible to vote';
END IF;
DBMS_OUTPUT.PUT_LINE(v_status);
END;DECLARE
i Number(3) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Count: ' || i);
i := i + 1;
EXIT WHEN i > 10;
END LOOP;
END;<a name="procedures"></a>
Procedures and functions are reusable blocks of code that perform specific tasks. The main difference is that procedures do not return a value, while functions do.
CREATE OR REPLACE PROCEDURE process_orders AS
BEGIN
-- PL/SQL code to process orders here
END;CREATE OR REPLACE FUNCTION calculate_average(p_numbers IN VarChar2)
RETURN Number
IS
v_sum Number(10,2) := 0;
v_count Number := 0;
v_number Number(10,2);
BEGIN
FOR i IN (SELECT TRIM(Number) FROM TABLE(JSON.GET_ARRAY(p_numbers, '*'))) LOOP
v_number := TO_NUMBER(i);
v_sum := v_sum + v_number;
v_count := v_count + 1;
END LOOP;
RETURN v_sum / v_count;
END;<a name="examples"></a>
BEGIN and END for proper PL/SQL block structure<a name="quiz"></a>
Which control structure is used for looping a specified number of times in PL/SQL?
That's all for today! Practice these concepts and you'll be on your way to mastering PL/SQL. Happy coding! 💡📝