PL/SQL Syntax Structure

 
Procedure:

PROCEDURE name (p_parm1 IN|INOUT datatype, … )
/* declarations */
IS
BEGIN
/* executable code */
EXCEPTION
/* error handling */
END name;
/

Function:

FUNCTION name name (p_parm1 IN|INOUT datatype, … )
RETURN datatype
/* declarations */
IS
BEGIN
/* executable code */
EXCEPTION
/* error handling */
END name;
/

Anonymous Block:

DECLARE
/* declarations */
IS
BEGIN
/* executable code */
EXCEPTION
:/* error handling */
END name;
/

All PL/SQL functions and procedures, including packaged procedures and anonymous blocks follow the above basic layout: If you don’t name the PL/SQL procedure, you call it an 'anonymous block'

CLOSE Syntax Statement

CLOSE cursor_name;

Closing a cursor releases the context area.

CURSOR Syntax Statement

CURSOR cursor_name
IS select_statement;

CURSOR cursor_name
[(parameter_name datatype, ...)]
IS select_statement;

Cursor parameters follow the syntax
cursor_parameter [IN] datatype [{:= | DEFAULT} expr]

Cursor Attributes

cursor%ROWCOUNT - int - number of rows affected by last SQL statement
cursor%FOUND - bool - TRUE if >1 row returned
cursor%NOTFOUND - bool - TRUE if 0 rows returned
cursor%ISOPEN - bool - TRUE if cursor still open

CURSOR in FOR LOOP Statement

When you use FOR-LOOP statement, all open, fetch, and close functions are inclusive.
Example:
BEGIN
FOR myrecord IN (SELECT c1, c2 FROM mytable) LOOP
-- implicit open/fetch occurs
IF myrecord.c1 = 1 THEN
.....
END IF;
END LOOP; -- implicit CLOSE occurs
END;
/

Cursor with Parameters
BEGIN
FOR trip_record IN trip_cursor(12, 3) LOOP ...

DECLARE Section

Declare variables and constants in a PL/SQL declare block.
name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]

key
name : The name of the variable
datatype : may be scalar, composite, reference or LOB
expr : a literal value, another variable or any plsql expression involving operators & functions.

A constant MUST have it's initial value in the declaration.
Composite datatypes are TABLE, RECORD, NESTED TABLE and VARRAY
You can use [schema.]object%TYPE to define variables based on actual object datatypes.

Declaring RECORD variables
A specific RECORD TYPE corresponding to a fixed number (and datatype) of underlying table columns can simplify the job of defining variables.
Syntax:
TYPE type_name IS RECORD
(field_declaration,...);

Options
'field_declaration' is defined as:
field_name {datatype | variable%TYPE | table.column%TYPE | table%ROWTYPE}[ [NOT NULL] {:= | DEFAULT} expr ]

Declare %ROWTYPE% Record variables:
DECLARE
variable_name table_name%ROWTYPE%
At runtime the system will evaluate the number of variables and their datatype; The columns may be based on an underlying table or a cursor.

Declare SQL*Plus bind variables.
Syntax:
SQL > VARIABLE g_bar VARCHAR2(30)
SQL > ACCEPT p_foo PROMPT 'enter the value required'
You can reference host variables in PL/SQL statements *unless* the statement is in a procedure, function or package. This is done by prefixing with & (to read the variable) or prefix with : (writing to the variable)

Example:
-- Declare a variable based on SQL*Plus Bind variable
v_amount NUMBER(6,2) := &p_foo

-- Assign value to a SQL*Plus variable from a PL/SQL variable
:g_bar := v_amount *12

Declare TABLE TYPE variables in a PL/SQL declare block.
Table variables are also known as index-by table or array. The table variable contains one column which must be a scalar or record datatype plus a primary key of type BINARY_INTEGER.
Syntax:
DECLARE
TYPE type_name IS TABLE OF
(column_type |
variable%TYPE |
table.column%TYPE
[NOT NULL]
INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type:
variable_name type_name;

-- Assigning values to a TABLE variable:
variable_name(n).field_name := 'some text'; -- Where 'n' is the index value

Using TABLE variable Methods:
To execute these use the syntax: table_name[ (parameters)]
EXISTS(n) Returns TRUE if nth element of the table exists.
COUNT The number of elements (rows) in the plsql table
FIRST First and Last index no.s in the table
LAST returns NULL if table is empty
PRIOR(n) Returns index no that preceeds n in the plsql table
NEXT(n) Returns index no that succeeds n in the plsql table
EXTEND(n,i) Append n copies of the 'i'th element to a plsql table i defaults to NULL n defaults to 1
TRIM(n) Remove n elements from the end of a plsql table n defaults to 1
DELETE(m,n) Delete elements in range m...n (m defaults to = n and n defaults to ALL elements

DECLARE, OPEN, CLOSE a REF CURSOR Syntax Statement

TYPE ref_type_name IS REF CURSOR
[RETURN {cursor_name%ROWTYPE
| ref_cursor_name%ROWTYPE
| record_name%TYPE
| record_type_name
| table_name%ROWTYPE} ];

Then: ref_cursor_name ref_type_name;

OPEN a REF cursor...
OPEN cursor_variable_name FOR select_statement;
CLOSE a REF cursor:
CLOSE {cursor_name | :host_cursor_variable_name};

Example:
IF NOT mycursor%ISOPEN THEN
OPEN mycursor FOR select_statement;
CLOSE mycursor;
END IF;

REF Cursor Attributes :
cursor%ROWCOUNT - int - number of rows affected by last SQL statement
cursor%FOUND - bool - TRUE if >1 row returned
cursor%NOTFOUND - bool - TRUE if 0 rows returned
cursor%ISOPEN - bool - TRUE if cursor still open

EXCEPTION Syntax

EXCEPTION
WHEN exception1 [OR exception2...]] THEN
...
[WHEN exception3 [OR exception4...] THEN
...]
[WHEN OTHERS THEN
...]

Where exception is the exception_name e.g. NO_DATA_FOUND, etc. Note that only one handler is processed before leaving the block.

Trap non-predefined errors by declaring them and using the PRAGMA EXCEPION_INIT pragma.
When an exception occurs you can identify the associated error code/message with two supplied functions SQLCODE and SQLERRM (SQLCODE – Number and SQLERRM – message)

If a sub block does not have a handler for a particular error it will propagate to the
enclosing block - where it can be caught by more general exception handlers.

RAISE_APPLICATION_ERROR (error_no, message[,{TRUE|FALSE}]);

FETCH Syntax Statement

FETCH cursor_name INTO [variable1, variable2,...]
| record_name;

The variables must match (both in number and positionally) the columns listed in the cursor definition.

FOR-LOOP Syntax Statement

FOR counter in [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
...
END LOOP;

A PL/SQL FOR Loop will implicitly declare a counter, or cursor variable. Remember that open, fetch, close functions are all implicit in the FOR-LOOP statement.

IF-THEN-END IF Syntax Statement

IF condition THEN
statements;
[ELSEIF condition THEN
statements;]
[ELSE
statement;]
END IF;

NOTE:
null AND null = null
null OR null = null
true AND null = null
true OR null = true
false AND null = false
false OR null = null
NOT NULL = NULL

LOOP Syntax Statement

LOOP
STATEMENT1;
...
EXIT [WHEN condition];
END LOOP;

OPEN Syntax Statement

OPEN cursor_name;
OPEN cursor_name param1 param2...;

PL/SQL Operators

Comparison Operators
+ - * / @ ; = <> != || <= >=
NOT IS NULL
LIKE
BETWEEN
IN
AND
OR

Comments
-- comment
/* comment */
<< Begin label - end label >>

Assignment operator
:=

Exponential operator (valid for plsql only)
**

Delimiters
Item separator .
Character string delimiter '
Quoted String delimiter "
Bind variable indicator :
Attribute indicator %
Statement terminator ;

Functions
All SQL functions that return a single row can be used in a plsql procedural statement. Note that the Group and DECODE functions are not supported.

Examples
v_myDate := TO_DATE('01-OCT-2001',DD-MON-YYYY)

WHILE-LOOP Syntax Statement

WHILE condition LOOP
statement1;
statement2;
...
END LOOP;