Basic Structure and Syntax of PL
Basic Structure and Syntax of PL
PL/SQL, groups the syntax of the programs into units called blocks.
These blocks can either named or unnamed.
The named blocks are called subprograms and unnamed blocks are called anonymous blocks.
Subprograms can be referred as either functions or procedures.
The difference between functions and procedures is that a function can be used in an expression and it
returns a value to that expression.
While a procedure is invoked as a standalone statement and passes values to the calling program only
through parameters.
Subprograms can be nested within one another and can be grouped in larger units called packages.
A block has three parts:
o A DECLARE section. In this section one can define local variables, constants, types, exceptions, and
nested subprograms.
o An EXECUTABLE section. In this is the actual code of a block gets executed. This part of the block
must be always present in the program.
o An EXCEPTION section. This section is used for handling runtime errors and warnings.
1.) The DECLARE Section
The DECLARE section begins with the keyword DECLARE and ends when the keyword BEGIN.
The next section that follows is the EXECUTABLE section.
One can declare types, constants, variables, exceptions, and cursors in any order, as long as they are
declared before they are referenced in the program.
Subprograms are declared at the end.
A semicolon terminates each definition.
Datatypes in PL/SQL provides a number of predefined data types for variables and constants.
It also enables you to define your own types.
The types fall into the following three categories:
o Scalar: These include all string, number, and binary types.
o Composite: These are structured data types. The PL/SQL composite types are TABLE and RECORD.
o Reference: There is one kind of reference data type--REF CURSOR--which is a pointer to a cursor..
In many cases, one can convert from one data type to another, either explicitly or automatically.
One can also define a variable so that it inherits its data type from a database column or from another
variable or constant.
The executable section is the main body of code. It consists primarily of SQL statements, flow control statements,
and assignments.
Assignments:
The assignment operator is: “=”For example, the following statement assigns the value ٤٥ to the variable a: a := ٤٥;
Character strings should be set off with single quotes (') as in all expressions. An example follows:
FNAME: = 'Clair';
Flow Control:
IF statements. These execute a group of one or more statements based on whether a condition is TRUE.
Basic loops. These repeatedly execute a group of one or more statements until an EXIT statement is reached.
FOR loops. These repeatedly execute a group of one or more statements a given number of times or until an EXIT
statement is reached.
WHILE loops. These repeatedly execute a group of one or more statements until a particular condition is met or an
EXIT statement is reached.
GOTO statements. These pass execution directly to another point in the code, exiting loops and enclosing blocks as
necessary. Use these sparsely, as they make code difficult to read and debug.
The EXCEPTION section begins with the keyword EXCEPTION and follows the END that matches the BEGIN of
the EXECUTABLE section.
It contains code that responds to runtime errors. An exception is a specific kind of runtime error.
When that kind of error occurs, you say that the exception is raised.
An exception handler is a body of code designed to handle a particular exception or group of exceptions.
Exception handlers, like the rest of the code, are operative only once the code is compiled and therefore can
do nothing about compilation errors.
There are two basic kinds of exceptions: predefined and user-defined.
The predefined exceptions are provided by PL/SQL in a package called STANDARD.
They correspond to various runtime problems that are known to arise often--for example, dividing by zero or
running out of memory.
The Oracle Server can distinguish between and track many more kinds of errors than the limited set that
STANDARD predefines
You can also define your own exceptions as will be shown.
It is usually better, however, to use Oracle exceptions where possible, because then the conditions are
tested automatically when each statement is executed, and an exception is raised if the error occurs.
The following illustrates the most basic anonymous block program, which does absolutely nothing other than run
without an error:
A block without an execution statement raises an exception because PL/SQL doesn’t support an empty block. For
example, this unnamed block fails:
Nested blocks are very common when we want to perform the certain process,
and at the same time, the code for these process should be kept in a separate
container (block).
Nested block concept will help the programmer to improve the readability by
separating the complex things into each block and to handle the exception for
each block inside the main outer block.
Each inner block is once again a PL/SQL block, hence all the properties and
characteristics of the inner block will be the same as outer block.
BEGIN
-- Executable section containing PL/SQL statements
BEGIN
-- Executable section containing PL/SQL statements specific to the local block
EXCEPTION
-- Exception handling specific to the local block
END block_name; -- Local block ends
1. Schema-Level Functions:
A schema-level function is a reusable piece of code that performs a
specific task and returns a value.
It is defined at the schema level, making it accessible to all users within
that schema.
Functions can be used to encapsulate logic, compute values, or perform
calculations that can be reused in various parts of the database.
Example of a schema-level function:
1. Integer:
Represents whole numbers without any fractional component.
Examples: int, integer , short, long in various programming languages.
2. Floating-Point:
Represents numbers with a fractional component.
Examples: float, double, real in various programming languages.
3. Character/String:
Represents a sequence of characters or a single character.
Examples: char, varchar, string, text in various programming languages
and databases.
1.) SQL> DECLARE
2.) lv_fixed CHAR(40) := 'Something not quite long.';
3.) lv_variable VARCHAR2(40) := 'Something not quite long.';
4.) BEGIN
5.) dbms_output.put_line('Fixed Length ['||LENGTH(lv_fixed)||']');
6.) dbms_output.put_line('Varying Length ['||LENGTH(lv_variable)||']');
7.) END;
8.) /
-----> It prints the space allocation sizes:
O/P:
Fixed Length [40]
Varying Length [25]
4. Boolean:
Represents logical values, typically true or false.
Examples: bool, boolean in various programming languages.
5. Date and Time:
Represents dates, times, or a combination of both.
Examples: date, time, datetime , timestamp in various programming
languages and databases.
6. Decimal/Numeric:
Represents fixed-point or floating-point numbers with a specified precision
and scale.
Examples: decimal , numeric in various programming languages and
databases.
7. Enumeration (Enum):
Represents a set of named constant values.
Examples: enum in various programming languages.
8. Char:
Represents a single character.
Examples: char in various programming languages.
9. Byte:
Represents a unit of digital information, typically 8 bits.
Examples: byte in various programming languages.
10. Short and Long:
Various programming languages may have short and long variants of
integer types to represent different ranges of values.
1. Arrays:
An ordered collection of elements, where each element is identified by an
index or a key.
Example: int[] in Java, array in PL/SQL.
2. Structures (structs):
A collection of elements, each with its own data type, grouped together
under a single name.
Example: struct in C, record in PL/SQL.
3. Records:
Similar to structures, records are used to group different data types under
a single name.
Example: record in Ada, struct in C++.
4. Classes:
In object-oriented programming, classes are composite data types that
encapsulate data and behavior.
Example: class in Java, C++, Python.
5. Tuples:
An ordered collection of elements, where each element may have a
different data type.
Example: tuple in Python, record in Ada.
6. Union Types:
A type that can hold values of different types, but only one at a time.
Example: union in C.
7. Enumerations with Data:
Enumerations that can also store additional data associated with each
value.
Example: enum with associated values in Swift.
8. Objects:
Instances of a class in object-oriented programming, combining data and
methods.
Example: object in various object-oriented programming languages.
Composite data types allow you to model complex structures and relationships within
your programs, making it easier to organize and manipulate data. They are
particularly useful when dealing with entities that have multiple attributes or when
you need to pass around related pieces of data as a single unit. The specific syntax
and features of composite data types can vary between programming languages, but
the underlying concept remains consistent.
CONTROL STRUCTURES:
1.) IF, ELSIF, AND ELSE STATEMENTS
SYNTAX:
IF condition THEN
-- code block to be executed if the condition is true
ELSIF condition2 THEN
-- code block to be executed if condition2 is true
ELSE
-- code block to be executed if none of the conditions are true
END IF;
EXAMPLE:
DECLARE
x NUMBER := 10;
BEGIN
IF x > 0 THEN
DBMS_OUTPUT.PUT_LINE('x is positive');
ELSIF x < 0 THEN
DBMS_OUTPUT.PUT_LINE('x is negative');
ELSE
DBMS_OUTPUT.PUT_LINE('x is zero');
END IF;
END;
/
It's important to use proper indentation and formatting to improve code readability.
Additionally, be aware that PL/SQL uses the THEN keyword after the IF and ELSIF
conditions. The code inside each block is enclosed between the THEN and the
corresponding END IF.
2.) CASE STATEMENTS In PL/SQL, the CASE statement is used for conditional control
flow similar to IF, ELSIF, and ELSE. It provides a concise way to handle multiple
conditions in a more readable and structured manner. The basic syntax for the CASE
statement is as follows:
SYNTAX:
CASE
WHEN condition1 THEN
-- code block to be executed if condition1 is true
WHEN condition2 THEN
-- code block to be executed if condition2 is true
...
ELSE
-- code block to be executed if none of the conditions are true
END CASE;
EXAMPLE:
DECLARE
x NUMBER := 10;
BEGIN
CASE
WHEN x > 0 THEN
DBMS_OUTPUT.PUT_LINE('x is positive');
WHEN x < 0 THEN
DBMS_OUTPUT.PUT_LINE('x is negative');
ELSE
DBMS_OUTPUT.PUT_LINE('x is zero');
END CASE;
END;
/
The CASE statement is often more concise and readable when you have multiple
conditions to check.
Each WHEN clause specifies a condition, and the first true condition (if any)
determines which block of code will be executed.
The ELSE block is optional and is executed if none of the previous conditions are
true.
Remember that both CASE and IF structures are available in PL/SQL, and the choice
between them often depends on the specific requirements and the readability of the
code.
EXCEPTION: