29
Introduction to PL/SQL15 Chapter 1 Introduction to PL/SQL Need for PL/SQL Benefits of Using PL/SQL PL/SQL Block Types and Constructs PL/SQL Block Structure Operators and SQL Functions in PL/SQL Variables Nested Blocks © SQL Star International Ltd 1

Chapter 1

Embed Size (px)

DESCRIPTION

Need for PL/SQL,Benefits of Using PL/SQL,PL/SQL Block Types and Constructs,PL/SQL Block Structure,Operators and SQL Functions in PL/SQL,Variables,Nested Blocks.

Citation preview

Page 1: Chapter 1

Introduction to PL/SQL15

Chapter 1

Introduction to PL/SQL

Need for PL/SQL Benefits of Using PL/SQL

PL/SQL Block Types and Constructs PL/SQL Block Structure Operators and SQL Functions in PL/SQL

Variables Nested Blocks

© SQL Star International Ltd 1

Page 2: Chapter 1

Introduction to PL/SQL15

Objectives

At the end of this chapter, you will be able to:

State the need for a procedural language in Oracle

Create PL/SQL blocks

Write nested blocks

© SQL Star International Ltd 2

Page 3: Chapter 1

Introduction to PL/SQL15

Introducing PL/SQLIn the journey so far, you have learnt about the Structured Query Language (SQL). The Oracle software provides a language, Procedural Language/SQL (PL/SQL), which is an extension of SQL.

PL/SQL implements modularity in the codes you write. It allows you to perform iterations and handle errors. Features like data hiding and error handling make PL/SQL a state-of-the-art language for databases.

PL/SQL also allows data manipulation and SQL query statements to be included within procedural units of code. This makes PL/SQL a powerful transaction processing mechanism.

Need for PL/SQLThe requirement for PL/SQL was mainly due to the need to centralize automated business tasks. For example, if each employee in an organization maintains separate programs to manage their tasks and updates them at their discretion, it could create confusions, such as:

• New employees or existing employees who are handed over someone else’s work, would have a problem understanding the process followed by the

employee vis-à-vis the organization

• Any change in business policy or functionality would have to be updated by all the employees individually in all relevant programs.

In a centralized functionality this is avoided because all changes need to be made at one place. Changes will get reflected in the relevant codes and all users can access updated information.

Benefits of Using PL/SQL

The reasons for using PL/SQL are as follows:

Integrating with the Oracle server and Oracle development tools

Implementing performance enhancements in an application

Modularizing the development of programs

Implementing Portability

Declaration of variables

Programming with procedural language control structures

Handling errors

© SQL Star International Ltd 3

Page 4: Chapter 1

Introduction to PL/SQL15

Integration

PL/SQL plays a key role in:

Oracle server, through stored procedures and functions, database triggers and packages

Oracle development tools, through Oracle Developer component triggers

PL/SQL supports the use of SQL datatypes. With direct access provided by SQL, these shared datatypes integrate PL/SQL with the Oracle server data dictionary. Hence, PL/SQL successfully bridges the gap between access to database technology and the need for procedural language capabilities.

Most applications such as Oracle Forms, Oracle Reports and Oracle Graphics, use shared libraries (that hold code), which can be accessed locally or remotely. To execute these stored codes, the Oracle tools have their own PL/SQL engine (independent of the engine present in the Oracle server). The engine first filters out the SQL statements to send them individually to the SQL statement executor in the Oracle server. It then processes the remaining procedural statements in the procedural statement executor in the PL/SQL engine. The procedural statement executor processes data, which is already inside the client environment and not in the database. This reduces the workload on the Oracle server and also the amount of memory required.

Performance Enhancements of Applications

When SQL statements are sent to the Oracle server one at a time, each statement results in a call to the Oracle server, leading to performance overhead and network traffic. If your application is SQL intensive, then instead of sending SQL statements individually to the server, you can put them into one block using PL/SQL and send the entire block to the server at one time. This reduces network traffic.

PL/SQL also operates with Oracle development tools, thereby adding procedural processing power to these tools and enhancing performance.

© SQL Star International Ltd 4

Page 5: Chapter 1

Introduction to PL/SQL15

Modularized Program Development

PL/SQL programs are made up of one or more blocks. These blocks may be individual ones or may be nested within another. That is, a block may represent a small part of another block, which may in turn be part of a whole unit of code. The units (procedures, functions or anonymous blocks) making up a PL/SQL program are called logical blocks.

A diagrammatic representation of modularization is:

The advantages associated with modularized development of programs are:

Logical groupings of related statements within blocks

Nesting blocks within larger blocks help build powerful programs

Breaking down complex problems into manageable sets of logical, well-defined modules, which can be implemented within blocks

Portability

PL/SQL is portable. That means, PL/SQL programs can be run wherever the Oracle server exists. There is no need to tailor them to suit each new environment. This is achieved because PL/SQL is native to the Oracle server, and therefore can be moved to any environment (operating system or platform) that supports the Oracle server.

PL/SQL code can also be moved between the Oracle server and Oracle Developer applications by writing programs and creating libraries in different environments.

Variable Declaration

© SQL Star International Ltd 5

Page 6: Chapter 1

Introduction to PL/SQL15

In PL/SQL, you can declare variables:

To use them in SQL and procedural statements

Belonging to different data types

Dynamically based on the structure of tables and columns in the database

Programming with Procedural Language Control Structures

PL/SQL allows the usage of control structures, which enable you to execute:

Sequence of statements conditionally Sequence of statements iteratively in a loop Individually the rows returned by multiple-row query

Handling Errors

PL/SQL implements error handling functionality by:

Processing Oracle server errors with error handling routines Declaring your own error conditions and process them with error handlers

PL/SQL Block Types and ConstructsThere are two block types and different types of constructs in PL/SQL. A block is a PL/SQL code. A construct is the way in which a block is written to implement different functionality.

Block Types

Logical blocks are the basic units of code that make up a PL/SQL program. The two kinds of PL/SQL blocks are:

Anonymous blocks Named blocks or Subprograms

Anonymous Blocks

Anonymous blocks are declared at that point in an application from where they are to be executed and are passed to the PL/SQL engine for execution at runtime. These blocks are unnamed blocks. They can be embedded in the iSQL*Plus environment. An application trigger consists of these blocks.

Subprograms

Unlike anonymous blocks, named blocks or subprograms are given a name. These blocks can be invoked for execution and they can also accept parameters.

Subprograms can be declared as Procedures or Functions. You declare a subprogram as a Procedure to perform an action, and you declare a subprogram as a Function to compute a value. Subprograms can be written and stored either at the server side or at the client side.

© SQL Star International Ltd 6

Page 7: Chapter 1

Introduction to PL/SQL15

Constructs

There are various PL/SQL program constructs available that use the basic PL/SQL block. The availability of program constructs depends on the environment in which they are executed.

The different program constructs are given below.

PL/SQL Block Structure

© SQL Star International Ltd 7

Page 8: Chapter 1

Introduction to PL/SQL15

To write a PL/SQL block, you need to know the different parts of a PL/SQL block and what each part should hold. The structure of all PL/SQL blocks is the same. The only difference is that, if it is an anonymous block it is not given a name.

A PL/SQL block has three sections . They are :

Declarative section Executable section Exception handling section

The declarative section is where the variables and constants used in the body of the block are declared. Any cursors or user-defined error handlers that are used in the body are declared here. This section is optional.

The executable section holds the set of statements or the logic of the tasks that are to be performed. You can include SQL statements to make changes to the database and PL/SQL statements to manipulate data in the block. The statements in this block are enclosed within the keywords BEGIN and END. This section is mandatory.

The last section of a block is the exception section. Here a set of statements is written to handle any errors that might occur when the statements in the executable section are being executed. This section is optional .

The diagramatic expression of PL/SQL block structure is given below.

© SQL Star International Ltd 8

Page 9: Chapter 1

Introduction to PL/SQL15

The syntax for writing a PL/SQL block is:

DECLARE<variable name> datatype(size);

BEGINSQL statements;PL/SQL statements;

EXCEPTIONWHEN <exception name> THEN…

END;/

Some points that will help you write a block:

A line of PL/SQL text which contains group of characters known as lexical units. These units are classified as follows:

Delimiters are simple or compound symbols that have a special meaning to PL/SQL. The following table presents both the simple as well as the compound symbols:

© SQL Star International Ltd 9

Page 10: Chapter 1

Introduction to PL/SQL15

Identifiers are used to name PL/SQL program constructs such as Constants, Variables and Exceptions. The following points need to be kept in mind while using identifiers:

• Identifiers can be up to 30 characters in length, but ensure they start with an alphabet.

• Do not give the same name for the identifiers as the name of columns in a table used in the block. If so, then the Oracle server assumes that the table column is being referred.

• An identifier consists of a letter, followed (optional) by other letters, numerals, underscores, dollar signs and number signs. The following characters are however illegal:

Abc&efg – illegal ampersandAbc-efg – illegal hyphenAbc/efg – illegal slashAbc efg – illegal space

• Identifiers should not be reserved words except when they are used within double quotes, for instance “INSERT”.

Literals are made up of definite values such as character, numeric, string or Boolean values, not represented by identifiers. These are case sensitive.

© SQL Star International Ltd 10

Page 11: Chapter 1

Introduction to PL/SQL15

Literals are of two types:

• Character literals: are all the printable characters such as letters, numerals, spaces, and special symbols. Specify character literals in single quotes.

• Numeric literals: are represented either by a simple value such as –12 or by a scientific notation such as 3E6.

Comments are extra information given by the programmer to improve readability in a code, to enable documenting in each phase and debugging.

PL/SQL code can be commented in two ways:

• Single line comment represented by --

• Multi line comment represented by /* */

Use a semicolon (;) at the end of all SQL and PL/SQL control statements and the

END keyword.

Do not use semicolons after the keywords DECLARE, BEGIN and EXCEPTION.

Increase the readability of the block by writing the keywords in uppercase.

Use a slash (/) to terminate a PL/SQL block on a line by itself.

Using Quotes in LiteralsOracle 10g allows you to define your own string delimiters to remove the need to double up any single quotes.

SET SERVEROUTPUT ON

BEGIN

--original code

DBMS_OUTPUT.PUT_LINE(‘He is New Jersey Library ‘’s Member!’);

-- using quote symbol

DBMS_OUTPUT.PUT_LINE(q’# He is New Jersey Library‘s Member!#’);

DBMS_OUTPUT.PUT_LINE(q’[ He is New Jersey Library‘s Member !]’);

© SQL Star International Ltd 11

Page 12: Chapter 1

Introduction to PL/SQL15

END;/

He is New Jersey Library‘s Member!He is New Jersey Library‘s Member!He is New Jersey Library‘s Member !

PL/SQL procedure successfully completed

Operators in PL/SQLThe following operators are supported in PL/SQL:

Arithmetic Logical Relational or Comparison Concatenation Exponentiation [Represented by (**)]

SQL Functions in PL/SQL StatementsAll the SQL functions can also be used in procedural statements in a block.

These include:

Single-row number and character functions

Datatype conversion functions

Date functions

Timestamp functions

GREATEST and LEAST functions

The functions that cannot be used in procedural statements are:

DECODE Group functions like AVG, MIN, MAX, COUNT, SUM, STDDEV and

VARIANCE. These functions work only on a group of rows in a table and hence, they can be used only with the SQL statements in a PL/SQL block.

VariablesA variable are named memory locations used to store data temporarily. The data stored in variables is used in the blocks and then processed. When the processing is completed, the data held in the variables may be written to the database or simply erased in case of session wide variables.

Why is a Variable used?

A Variable stores data temporarily. It manipulates the stored data and performs calculations with the data without accessing the database. Once declared, variables can be used repeatedly in an application by referencing them in other statements in the block.

© SQL Star International Ltd 12

Page 13: Chapter 1

Introduction to PL/SQL15

When variables are declared using %TYPE and %ROWTYPE (more information is provided later in the chapter), you are infact basing the variable declaration on the column definition of a table. In this case, if the column definition changes, then the variable declarations also changes accordingly. This helps in data independence, reduces maintenance cost and allows the program to adjust to the new business logic.

How to handle variables in PL/SQL?

In a PL/SQL block, variables are:

Declared and initialized in the declarative section of the block.

Assigned new values in the executable section. On doing so, the existing value is replaced with the newly assigned value. Care must be taken to see that a variable being referred to is already declared in the declarative section. Forward references cannot be made.

Types of Variables

Variables are of two types. They are:

PL/SQL variables

Non-PL/SQL variables

PL/SQL Variables

PL/SQL variables have a data type that specifies a storage format, constraints and also valid range of values. The data types used to declare PL/SQL variables are:

Scalar data types are those that correspond to database column types. These data types hold only a single value. The base scalar data types include:

CHAR VARCHAR2 LONG LONG RAW NUMBER BINARY_INTEGER PLS_INTEGER BINARY_FLOAT BINARY_DOUBLE BOOLEAN DATE TIMESTAMP TIMESTAMP WITH TIMEZONE TIMESTAMP WITH LOCAL TIMEZONE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND

Binary_Float and Binary_Double are the two new Datatypes introduced in Oracle10g.They represent floating point numbers in IEEE 754 format (Institute of Electrical and Electronic Engineers) and require 5 byte and 9 bytes to store the values respectively. IEEE format s supported by most of the computer system

© SQL Star International Ltd 13

Page 14: Chapter 1

Introduction to PL/SQL15

operating through native processor instructions thereby helping us to carry out complex computations using floating point data.

Composite data types are those that are defined by users. They enable you to

manipulate groups of data in PL/SQL blocks

Reference data types are those that hold values pointing to other objects. These are also known as pointers.

LOB (large object) data types: are those that hold values, which specify the location of large objects such as graphic images. These values are known as locators. Large objects are stored in the same database as the table but not within the table. LOB data type allows you to store unstructured data of a maximum of 8-128 terabytes. This data could be a movie clip or a graphic image or a sound wave form. LOBs are further classified into:

CLOB (Character Large Objects) is used to store large blocks of character data of a single byte.

BLOB (Binary Large Object) is used to store large binary objects within the database.

BFILE (Binary File) is used to store large binary objects that are in the operating system files outside the database.

NCLOB (National Language Character Large Objects), are used to store large

blocks of NCHAR data that may be single-byte or fixed-width multiple bytes

The syntax for declaring PL/SQL variables is:

identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

Where,

identifier is the name assigned to the variable declared.

CONSTANT specifies a constraint that the value of the variable cannot change. Constant variables must be initialized. While declaring a variable as a constant, the CONSTANT keyword must precede the datatype specification.

DATATYPE specifies the type of data the variable can hold. It could be scalar, composite, reference or LOB datatype.

NOT NULL specifies a constraint that the variable must contain a value. Therefore, NOT NULL variables must be initialized.

:= is the assignment operator used to assign an expression to a variable. Instead of the assignment operator, the DEFAULT expr (expression) can be used to assign values to the variables.

By default, all variables are initialized to NULL. To prevent null values, variables are initialized using the DEFAULT keyword.

The following code snippet shows how PL/SQL variables are declared in the declarative section of a block:

© SQL Star International Ltd 14

Page 15: Chapter 1

Introduction to PL/SQL15

DECLAREFirstName CHAR(20);BranchID CHAR(7) NOT NULL: = ‘09RANNJ’;FeeAmt CONSTANT NUMBER(2): = 15;CatgName CHAR(15) DEFAULT ‘Fiction’;

% TYPE Attribute

If you need to store a database column value in a variable or write a value from a variable to a database column, then the data type of the variable needs to be the same as that of the database column. You can use the %TYPE attribute to declare a variable to be of the same data type as that of a previously declared variable or database column.

Incorrect variable data types generate PL/SQL errors during execution. When you want to declare a variable using a table attribute instead of the datatype the syntax is

<variable_name> table.columnname%TYPE

For example, in case you want to declare a variable that will store the address of a library member, you will write in the following syntax:

DECLAREAddress VARCHAR2(45);

But, the above declaration will result in an error when an attempt is made to populate the variable with address details of members from the database table. This is because there is a mismatch in type specification of the variable. The datatype width of the vAddress column in table Member is 50, but you have declared it as 45. To overcome this, declare the variable using %TYPE attribute as follows:

DECLAREAddress Member.vAddress%TYPE;

This statement declares a variable whose datatype and width is based on the vAddress column.

If you want to declare a variable of the same type as a previously declared variable then the syntax is

<variable_name> variable_name%TYPE

Using %TYPE attribute to declare a variable based on a previously declared variable, is illustrated in the section dealing with the iSQL*Plus variables within PL/SQL blocks.Datatype and Variable size is determined when the block is compiled. So even if there is a change in the database column datatype the code manages the changed datatype information.

© SQL Star International Ltd 15

Page 16: Chapter 1

Introduction to PL/SQL15

Data Conversion Functions

In any programming language generally, we have to deal with different datatypes simultaneously or receive data which is not in the default format. In such cases, Oracle server implicitly converts data into valid datatypes wherever feasible. Explicit conversions come into the scenario where automatic conversions are not possible.

Oracle Server takes care of implicit conversion between 1. Character and Number 2. Character and Date

But how is it done? Let us take an example.

DECLARE cons_nfine NUMBER(3):=50; cons_extra_fine VARCHAR2(20):=’5'; tot_fine Transaction.nfine%TYPE;

BEGIN tot_fine:= cons_nfine+cons_extra_fine; DBMS_OUTPUT.PUT_LINE(‘The total fine payable is Rs.‘||tot_fine);

END;/

So, did you notice something?Variable cons_nfine is of number datatype and cons_extra_fine is of VARCHAR2 datatype. While assigning the result to tot_fine variable, cons_extra_fine is converted to number by PL/SQL executer and then the operation is performed.

© SQL Star International Ltd 16

Page 17: Chapter 1

Introduction to PL/SQL15

To perform explicit conversion, following built in functions can be used.to_char()to_number()to_date()to_Binary_float()to_Binary_double()

DECLARE v_Date date:= to_Date( ‘April 04 2007’,’Month dd YYYY’);

BEGIN DBMS_OUTPUT.PUT_LINE(‘You have entered ‘ ||v_Date ||’ as input’);

END;/

Example to show the usage of new datatypes.

DECLARE

l_binary_float BINARY_FLOAT;

l_binary_double BINARY_DOUBLE;

BEGIN

l_binary_float := 2.1f;

l_binary_double := 2.00001d;

DBMS_OUTPUT.PUT_LINE(l_binary_double);

DBMS_OUTPUT.PUT_LINE(l_binary_float);

l_binary_float := TO_BINARY_FLOAT(2.1);

l_binary_double := TO_BINARY_DOUBLE(2.00001);

DBMS_OUTPUT.PUT_LINE(l_binary_double);

DBMS_OUTPUT.PUT_LINE(l_binary_float);

END;

/

© SQL Star International Ltd 17

Page 18: Chapter 1

Introduction to PL/SQL15

Non-PL/SQL Variables

Since PL/SQL has neither input nor output capabilities, it relies on the environment in which it is executed in order to pass values into and out of a PL/SQL block.

The following non-PL/SQL variables can be used within PL/SQL blocks:

Substitution variables Host variables

Substitution variables are those that you can use to pass values to a PL/SQL block at runtime. To reference a substitution variable in a block, prefix it with an ampersand (&). Before the block is executed the values for the variables are substituted with the values passed.

Hence, you cannot input different values for the substitution variables using a loop. The substitution variable can be replaced only by one value.Here is an example showing the use of substitution variables within PL/SQL blocks. Suppose, the library wants to calculate its quarterly income based on its annual income. To do this, it declares a substitution variable, which would prompt the user to enter the figure of annual income. Based on the value entered, the quarterly income would be calculated.

DECLAREAnnualIncome NUMBER (7): = &annualinc;QuarterlyInc AnnualIncome%TYPE;-—declaring variable based on previously declared variable

using --%TYPE attribute.BEGIN

QuarterlyInc:= AnnualIncome/4;DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library

is: ’|| QuarterlyInc);END;/

In the above block, to display the quarterly income calculated, you can specify the DBMS_OUTPUT.PUT_LINE in the PL/SQL block. DBMS_OUTPUT is an Oracle supplied package and PUT_LINE is a procedure within it. To use this you need to specify the information you want printed, in parentheses, following the DBMS_OUTPUT.PUT_LINE command as shown in the above code:

DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library is: ’|| QuarterlyInc);

For DBMS_OUTPUT.PUT_LINE to work, you need to run the iSQL*Plus command SET SERVEROUTPUT ON.

iSQL*Plus host variables (also known as bind variables) are used to pass runtime values from the PL/SQL block back to the iSQL*Plus environment. These variables can be referenced in a PL/SQL block by placing a colon(:) before the variable.

The keyword VARIABLE is used to declare a bind variable. The syntax is:

© SQL Star International Ltd 18

Page 19: Chapter 1

Introduction to PL/SQL15

VARIABLE <variable_name> datatype

The syntax to display the variable value is:

PRINT <variable_name>

Bind variables cannot be referred within the PL/SQL block of a function, procedure or a package.

In a PL/SQL block, to differentiate between host variables and declared PL/SQL variables, prefix the former with a colon(:).

The code wherein you had calculated the quarterly income using substitution variables can be re-written using host variables as follows:

VARIABLE QuarterlyInc NUMBERDECLARE

AnnualIncome NUMBER(7):= &AnnInc;BEGIN

:QuarterlyInc:= AnnualIncome/4;END;/old 2: AnnualIncome NUMBER(7):= &AnnInc;new 2: AnnualIncome NUMBER(7):= 80000;

PL/SQL procedure successfully completed.

PRINT QuarterlyInc

QUARTERLYINC------------ 20000

The above example shows the Host variable being assigned a value inside a PL/SQL block. To assign a value to a host variable outside the Pl/SQL block following can be done:-

SQL > VARIABLE QuarterlyInc NUMBERSQL > Exec :QuarterlyInc := 20000SQL> PRINT QuarterlyInc

QUARTERLYINC------------ 20000

Where, Exec stand for Execute privilege.

© SQL Star International Ltd 19

Page 20: Chapter 1

Introduction to PL/SQL15

Nested BlocksPL/SQL allows blocks to be nested wherever you can have an executable statement. [This makes the nested block a statement.] Hence, the executable part of a block can be broken down into smaller blocks. Even the exception section can contain nested blocks.

Variable Scope

Issues that concern references to identifiers can be resolved taking into account their scope and visibility. By scope, we mean that region of a program unit from which an identifier can be referenced. For instance, a variable in the declarative section can be referenced from the exception section of that block.

The diagram shown below illustrates the concept of nested blocks and variable scope.

By visibility, we mean the regions from which an identifier can be referenced without using a qualified name.

The following code snippet shows how to qualify identifiers:

© SQL Star International Ltd 20

Page 21: Chapter 1

Introduction to PL/SQL15

<<outer_blk>> --Block label DECLARE --This is the parent block

JoiningDt DATE;BEGIN

DECLARE --his is the child blockJoiningDt DATE;

BEGIN…

outer_blk.JoiningDt :=TO_DATE (’20- JAN-1998’, ‘DD-MON-YY’);

END;…END;/

In the code snippet, a variable with the same name as the variable declared in the outer block is declared in the inner block. To reference the outer block variable in the inner block, the variable is qualified by prefixing it with the block name.Identifiers are considered local to the PL/SQL block in which they are declared, and are considered global to all its sub-blocks. Within the sub-block, only local identifiers are visible because to reference the global identifiers you must use a qualified name. If a block cannot find the identifier declared locally, it will look up to declarative section of the enclosing block (parent block). However, the block will never look down to the enclosed blocks (child blocks).

Look at the following code and determine the variable scope:

<<OUTER_BLK>>DECLARE

vSal NUMBER(8,2) := 50000;vComm NUMBER(8,2) := vSal * 0.10;vNote VARCHAR2(200) := ‘Eligible for commission’;

BEGINDECLARE

vSal NUMBER(8,2) := 90000;vComm NUMBER (4) := 0;vAnnualComp NUMBER(8,2) := vSal + vComm;

BEGINvNote := ‘Manager not’||vNote;

OUTER_BLK.vComm := vSal * 0.20; END; vNote := ‘Salesman’||vNote;

END;/

Based on the rules of scoping, determine values of:

© SQL Star International Ltd 21

Page 22: Chapter 1

Introduction to PL/SQL15

vNote at position 1 vAnnualComp at position 2 vComm at position 1 OUTER_BLK.vComm at position 1 vComm at position 2 vNote at position 2

Guidelines for Writing PL/SQL Code

Programs can be indented using carriage return,tabs and aligning keywords in the same line at different levels.Writing so, the task of debugging is made simpler.While writing programs we can follow a case convention, though PL/SQL is not case sensitive. For instance:-

• All keywords should be written in uppercase. • They must be aligned in the same line. • Table names and column names are to be in Initcap and lower case

respectively.

Indented programs improve the performance in those cases where similar statements are to be issued repeatedly because there is no need to parse the statements again.

Let us write a program following all the rules stated above.

DECLARE AnnualIncome NUMBER(7):= 60000;QuarterlyInc NUMBER(8,2);

BEGINQuarterlyInc:= AnnualIncome/4;DBMS_OUTPUT.PUT_LINE(‘The Quarterly income is ‘||

QuarterlyInc);END;

/

Here, the keywords are aligned in the same line but at different levels. This improves readability of the code.

Summary

In this chapter, you have learnt that:

© SQL Star International Ltd 22

Page 23: Chapter 1

Introduction to PL/SQL15

PL/SQL bridges gap between SQL and a procedural language.

Two types of PL/SQL blocks are:

1. Anonymous or unnamed blocks which are not stored in database and compiled each time they are executed.

2. Named Blocks which are compiled only once and stored in the database.

The three sections of a PL/SQL Block are:

1. Declarative Section, where all the variables used in the program are declared. This is optional. Keyword: DECLARE

2. Executable Section where actual logic of the program lies. Keyword: BEGIN

3. Exception Section where all the errors are handled. This section is optional. Keyword: EXCEPTION

4. END to end the PL/SQL program.

PL/SQL variables are declared and are accessible only within that PL/SQL block. Non- PL/SQL variables are declared outside the PL/SQL block and are available throughout the session.

Two new datatypes FLOAT and DOUBLE introduced in this release help users in computing complex calculations.

Nesting of blocks is allowed to have good control on the scope of the variables. Nested Blocks can also have exception sections.

© SQL Star International Ltd 23

Page 24: Chapter 1

Introduction to PL/SQL15

Lab Exercises

1. Identify whether the following declarations are correct or incorrect:

a) DECLARE empID NUMBER(5);

b) DECLARE str1, str2, str3 VARCHAR2(20);

c) DECLARE hiredate DATE NOT NULL;

d) DECLARE on BOOLEAN := 5;

2. Create an anonymous block to display the phrase “Welcome to the world of PL/SQL”.

3. Create a block that declares two variables, one of VARCHAR2 type and the other of NUMBER type. Assign the following values to the variables and display the output on the screen.

4. Write a PL/SQL code to display the ID, Last Name, job ID and salary of an employee?

5. Among the following which datatypes are enhancements of Oracle10g?

© SQL Star International Ltd 24

Page 25: Chapter 1

Introduction to PL/SQL15

a) BINARY_INTEGER b) BINARY_FLOAT

c) BINARY_DOUBLE

6. Display the following text using quote operator q: I’m Oracle certified,you’re not.

© SQL Star International Ltd 25