0% found this document useful (0 votes)
4 views

Basic Structure and Syntax of PL

PL/SQL organizes code into blocks, which can be named (subprograms) or unnamed (anonymous). Each block consists of a DECLARE section for variable declarations, an EXECUTABLE section for code execution, and an EXCEPTION section for error handling. PL/SQL supports various data types, control structures, and allows for nested blocks to enhance code organization and readability.

Uploaded by

Hafsa Fatima
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Basic Structure and Syntax of PL

PL/SQL organizes code into blocks, which can be named (subprograms) or unnamed (anonymous). Each block consists of a DECLARE section for variable declarations, an EXECUTABLE section for code execution, and an EXCEPTION section for error handling. PL/SQL supports various data types, control structures, and allows for nested blocks to enhance code organization and readability.

Uploaded by

Hafsa Fatima
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Basic Structure and Syntax of PL/SQL

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.

2.) The EXECUTABLE Section

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:

PL/SQL supports the following kinds of flow-control statements:

 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.

3.) The EXCEPTION Section

 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.

BASIC STRUCTURE OF PL/SQL:


DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

The following illustrates the most basic anonymous block program, which does absolutely nothing other than run
without an error:

1.) SQL> BEGIN


2.) NULL;
3.) END;
4.) /

A block without an execution statement raises an exception because PL/SQL doesn’t support an empty block. For
example, this unnamed block fails:

1.) SQL> BEGIN


2.) END;
3.) /

 It raises the following exception: END; * ERROR at line 2


BEHAVIOUR OF VARIABLES:

 A variable is nothing but a name given to a storage area that our
programs can manipulate.
 Each variable in PL/SQL has a specific data type, which determines the
size, the layout of the variable's memory {the range of values that can
be stored within that memory} and the set of operations that can be
applied to the variable.
 The name of a PL/SQL variable consists of a letter optionally followed by
more letters, numerals, dollar signs, underscores, and number signs and
should not exceed 30 characters.
 By default, variable names are not case-sensitive.
 You cannot use a reserved PL/SQL keyword as a variable name.
 PL/SQL programming language allows to define various types of
variables, such as date time data types, records, collections, etc

Variable Declaration in PL/SQL:


 PL/SQL variables must be declared in the declaration section or in a
package as a global variable.
 When you declare a variable, PL/SQL allocates memory for the
variable's value and the storage location is identified by the variable
name.

The syntax for declaring a variable is −

variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

1.) ANONYMOUS BLOCKS:


 Variable names begin with letters and can contain alphabetical characters,
ordinal numbers (0 to 9), and the $, _, and # symbols.
 Variables have local scope only, which means they’re available only in the
scope of a given PL/SQL block.
 The exceptions to that rule are nested anonymous blocks.
 Nested anonymous blocks operate inside the defining block.
 In PL/SQL, The blocks which is do not have header are known as
anonymous blocks.
 These blocks do not form the body of a function or triggers or procedure.
 Example: Here a code example of find greatest number with Anonymous
blocks.
EXAMPLE PROGRAM:

2.) NESTED ANONYMOUS BLOCKS:

 In PL/SQL, each block can be nested into another block.

 They are referred as a nested block.

 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.

Nested Block Structure


 A block can be nested into another block.
 This can be nested either in the execution part or in the exception
handling part. These block can also be labeled.

 One outer block can contain many inner blocks.

 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.

3.) Named blocks:


 That’s PL/SQL blocks which having header or labels are known as Named
blocks.
 These blocks can either be subprograms like functions, procedures,
packages or Triggers.
 Example: Here a code example of find greatest number with Named
blocks means using function.
Both type of PL/SQL blocks are further divided into 3 different sections which are:

1. The Declaration Section


2. The Execution Section and
3. The Exception-handling Section

{DECLARATION, EXCEPTION, EXECUTION PART}

Local named block:


In PL/SQL (Procedural Language/Structured Query Language), a local named block is a
section of code within a PL/SQL program that is given a name and can be called or
executed explicitly. This provides a way to organize and encapsulate logic within a
program.

Here's a basic structure of a local named block in PL/SQL:


DECLARE
-- Declaration section for variables and constants

BEGIN
-- Executable section containing PL/SQL statements

<<block_name>> -- Declaration of the local named block


-- Local block starts
DECLARE
-- Declaration section for variables and constants specific to the local block

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

-- More PL/SQL statements outside the local block


EXCEPTION
-- Global exception handling for the entire block
END;

In the example above:

 The DECLARE section is used for declaring variables and constants.


 The main BEGIN and END block contains the main executable section of the program.
 The <<block_name>> syntax declares a local named block with the specified name.
 Within the local block, you can have a separate DECLARE section for variables and
constants specific to that block.
 The executable section within the local block contains the specific logic for that block.
 Exception handling can be done both globally for the entire block and locally for the specific
block.
Local named blocks are useful for organizing code, improving readability, and encapsulating logic
that may need to be called separately within the program. They also allow for more fine-grained
exception handling within specific sections of the code.

STORED NAMED BLOCKS:

In a database system, a schema is a collection of database objects, including tables,


views, indexes, and programmatic constructs such as functions and procedures.
Schema-level functions and procedures are those that are created at the schema level
rather than at the individual user level. These objects are typically shared across
multiple users within the same schema.

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:

CREATE OR REPLACE FUNCTION schema_level_function


RETURN NUMBER
IS
result_value NUMBER;
BEGIN
-- Logic to compute the result_value
result_value := 42;
RETURN result_value;
END schema_level_function;
/
In this example, schema_level_function is a function defined at the schema level.
2. Schema-Level Procedures:
 A schema-level procedure is a named set of PL/SQL statements that can
be executed as a unit.
 Like functions, procedures are created at the schema level and are
accessible to all users within that schema.
 Procedures can be used for encapsulating a series of SQL and PL/SQL
statements to perform a specific task.
Example of a schema-level procedure:

CREATE OR REPLACE FUNCTION schema_level_function


RETURN NUMBER
IS
result_value NUMBER;
BEGIN
-- Logic to compute the result_value
result_value := 42;
RETURN result_value;
END schema_level_function;
/
In this example, schema_level_procedure is a procedure defined at the schema level.
SCALAR DATA TYPES:
Scalar data types, in the context of programming and databases, refer to data types
that hold a single value. Unlike composite data types (e.g., arrays, structures, or
objects), scalar data types represent a single value at a time. Scalar data types are
fundamental building blocks in programming languages and database systems.
Common scalar data types include:

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.

COMPOSITE DATA TYPE:


Composite data types, also known as structured or aggregate data types, allow you to
combine multiple values into a single variable. These types are useful for representing
more complex data structures. Common composite data types include:

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;
/

Here are some key points to note:

 You can have multiple ELSIF blocks to check additional conditions.


 The ELSE block is optional and is executed if none of the previous conditions are
true.
 The conditions are evaluated in order, and the first true condition (if any)
determines which block of code will be executed.

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;
/

Key points to note:

 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.

1.) WHILE LOOP:


DECLARE
i NUMBER := 1;
BEGIN
WHILE i <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration ' || i);
i := i + 1;
END LOOP;
END;
/
In this example, the loop continues as long as the value of i is less than or equal to 5.

2.) FOR LOOP:


DECLARE
-- Loop variable implicitly declared and initialized
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration ' || i);
END LOOP;
END;
/
In this example, the loop iterates from 1 to 5, and the loop variable i is implicitly declared
and incremented.

3.) LOOP-EXIT LOOP:


DECLARE
i NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Iteration ' || i);
i := i + 1;
EXIT WHEN i > 5;
END LOOP;
END;
/
In this example, the loop continues indefinitely until the EXIT WHEN condition is met.

EXCEPTION:

You might also like