Introducing PL/SQL block structure and anonymous block
PL/SQL program units organize the code into blocks. A block without name is known as anonymous block. The anonymous block is the simplest unit in PL/SQL. It is called anonymous block because it is not saved in the database. The anonymous blocks are only one-time use and useful in certain situations such as creating test units. The following illustrates anonymous block syntax:[DECLARE]
Declaration statements;
BEGIN
Execution statements;
[EXCEPTION]
EXCEPTION handling statements;
END;
/
The anonymous block has three basic parts that are declaration, execution, and exception handling. Only execution part is required and the others are optional.
- The declaration part allows you to define data types, structures, and variables. You can also declare a variable in the declaration part by giving it a name, a data type and a initial value. You can both define and declare variables in the declaration part.
- The execution part is required in block structure and it must have at least one statement. The execution part is where you put the execution code or business logic. You can use both procedural and SQL code inside execution part.
- The exception handling part is starting with the keyword EXCEPTION. The exception part is where you put the code to manage exceptions. You can either catch or handle exceptions in this part.
PL/SQL block structure examples
Let’s take a look at the simplest block that does nothing.BEGIN
NULL;
END;
Now if we want to output it on screen we execute the following block:
SET SERVEROUTPUT ON SIZE 1000000
BEGIN
DMBS_OUTPUT.PUT_LINE('Hello PL/SQL');
END;
/
In the above examples, you just uses the execution part to execute code. You will learn how to declare variables and handling exceptions in the next tutorials.
Exercise on anonymous block structure
Now it is your turn to create a block and execute it in SQL*Plus that print a greeting message “Hello Word” on screen.First, you need to login to the SQL*Plus by the account by providing username and password as the figure 1 below.
Second, type the following code into the SQL*Plus and execute it as the figure 2 below:
Congratulation, you’ve finished the first PL/SQL program!