Learnitweb

PL/SQL – Basic Syntax

1. Introduction

In this tutorial, we’ll discuss basic syntax of PL/SQL. There are three parts of PL/SQL subprogram.

Declaration partThis section starts with the DECLARE. This section is used for declarations of local types, variables and subprograms. This section is optional. Declarations are local to the block and cease to exist when the block completes execution.
Executable partThis part starts with BEGIN and ends with END. This is a mandatory section. This section contains executable statements. It should have at least one executable line of code, which may be just a NULL command to indicate that nothing should be executed.
Exception-handling partThis is an optional part. This sections contains exception handlers for exceptions (errors) raised in executable part. This section starts with the EXCEPTION.

PL/SQL blocks can be nested. Since a PL/SQL block is an executable statement, it can appear in another block wherever an executable statement is allowed.

2. Basic structure of PL/SQL blocks

The basic structure of a PL/SQL block looks like the following:

<< label >> (optional)
DECLARE -- Declarative part (optional)
-- Declarations of local types, variables and subprograms

BEGIN -- Executable part (required)
-- Executable statements

[EXCEPTION -- Exception-handling part (optional)
-- Exception handlers for exceptions (errors) raised in executable part]
END;

3. Hello World Example

In this example, we’ll print a message on the console.

DECLARE 
   message  varchar2(20):= 'Hello, World!'; 
BEGIN 
   dbms_output.put_line(message); 
END;

Output

Hello, World!

PL/SQL procedure successfully completed.

We’ll use SQL Developer tool to run the code. To run the code from the SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code.