Sub topic 1
Anatomy of a PL/SQL block
Prerequisites
This chapter assumes you know basic SQL statements (SELECT, INSERT, UPDATE, DELETE), recognize Oracle data types such as NUMBER and VARCHAR2, and can run statements in SQL*Plus, SQL Developer, or SQLcl. You need access to a schema with a sample table such as HR.EMPLOYEES.
Anatomy of a PL/SQL block
A PL/SQL block is the basic unit of PL/SQL code. It has up to three sections:
- DECLARE: optional. Declares variables, constants, and other names.
- BEGIN ... END: required. Holds the executable statements.
- EXCEPTION: optional. Handles errors raised in the executable section.
Anonymous blocks and named blocks
An anonymous block has no name. You type it into a script or client, it runs once, and it is not stored in the database. A named block is a stored procedure or function. It has a name, and other programs can call it. This chapter uses anonymous blocks.
Printing results with DBMS_OUTPUT
DBMSOUTPUT is a built-in package. Its PUTLINE procedure writes a line of text that your client can display. SQL*Plus and SQLcl show this text only after you run SET SERVEROUTPUT ON.
The declaration section
The DECLARE section defines the names your code uses. Each variable needs a name and a data type. A variable can also start with a value and can be marked as NOT NULL.
Declaring and naming variables
Use this syntax: name datatype [NOT NULL] [:= value];
SET SERVEROUTPUT ON
DECLARE
c_tax_rate CONSTANT NUMBER(4,3) := 0.075;
v_message VARCHAR2(50) := 'Hello, PL/SQL';
v_price NUMBER(10,2) NOT NULL := 100;
v_total NUMBER(10,2);
BEGIN
v_total := v_price * (1 + c_tax_rate);
DBMS_OUTPUT.PUT_LINE(v_message);
DBMS_OUTPUT.PUT_LINE('Total: ' || v_total);
END;
/The block prints Hello, PL/SQL and then Total: 107.5.
Name variables with a letter first, up to 30 characters, and no reserved words. A common convention is the prefix v for variables and c for constants. A CONSTANT keeps its value for the whole block. A NOT NULL variable must have an initial value, or the block fails to compile.
Exercise
Exercise
What happens if you remove SET SERVEROUTPUT ON and run the block?
Show answer
The block runs, but no text appears. The client shows DBMS_OUTPUT text only when server output is turned on.
Exercise
Why does declaring v_price with NOT NULL require an initial value?
Show answer
A variable with no value starts as NULL, which NOT NULL forbids. Without an initial value, PL/SQL rejects the declaration with a compile error (PLS-00218).