Professional Documents
Culture Documents
PLSQL Self Notes
PLSQL Self Notes
PLSQL
In Oracle database management, PL/SQL is a procedural language extension to Structured Query Language
(SQL). The purpose of PL/SQL is to combine database language and procedural programming language.
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL. PL/SQL is one of
three key programming languages embedded in the Oracle Database, along with SQL itself and Java.
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural
extension language for SQL and the Oracle relational database. Following are certain notable facts about
PL/SQL −
PL/SQL can also directly be called from the command-line SQL*Plus interface.
Direct call can also be made from external programming language calls to database.
PL/SQL's general syntax is based on that of ADA and Pascal programming language.
Apart from Oracle, PL/SQL is available in Times Ten in-memory database and IBM DB2.
Features of PL/SQL
PL/SQL has the following features −
SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL
supports both static and dynamic SQL. Static SQL supports DML operations and transaction control
from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in PL/SQL blocks.
PL/SQL allows sending an entire block of statements to the database at one time. This reduces
network traffic and provides high performance for the applications.
PL/SQL gives high productivity to programmers as it can query, transform, and update data in a
database.
PL/SQL saves time on design and debugging by strong features, such as exception handling,
encapsulation, data hiding, and object-oriented data types.
PL/SQL provides support for developing Web Applications and Server Pages.
It combines the data manipulation power of SQL with the processing power of procedural language to create
super powerful SQL queries.
PL/SQL means instructing the compiler 'what to do' through SQL and 'how to do' through its procedural
way.
Similar to other database languages, it gives more control to the programmers by the use of loops, conditions
and object-oriented concepts.
Architecture of PL/SQL
1. PL/SQL block
2. PL/SQL Engine
3. Database Server
PL/SQL block:
PL/SQL Engine
PL/SQL engine is the component where the actual processing of the codes takes place.
PL/SQL engine separates PL/SQL units and SQL part in the input (as shown in the image below).
The separated PL/SQL units will be handled by the PL/SQL engine itself.
The SQL part will be sent to database server where the actual interaction with database takes place.
It can be installed in both database server and in the application server.
Database Server:
This is the most important component of Pl/SQL unit which stores the data.
The PL/SQL engine uses the SQL from PL/SQL units to interact with the database server.
It consists of SQL executor which parses the input SQL statements and execute the same.
why ?
begin
null;
end;
BEGIN
-----MIN one statement
END;
BEGIN
dbms_output.put_line('Welcome');
END;
BEGIN
dbms_output.put_line('Welcome');
dbms_output.put_line('hi');
dbms_output.put_line('hello');
dbms_output.put_line('Welcome');
END;
BEGIN
dbms_output.put_line('Welcome'||' greens');
END;
DECLARE --optional
<Declarations>
BEGIN --mandatory
<executable statements. At least one executable statement is mandatory>
EXCEPTION --optional
<exception handles>
END; --mandatory
/
Note: A block should always be followed by '/' which sends the information to the compiler about the end of
the block.
Types of PL/SQL block
PL/SQL blocks are of mainly two types.
Anonymous blocks
Named Blocks/Subprograms
Anonymous blocks:
Anonymous blocks are PL/SQL blocks which do not have any names assigned to them. They need to be
created and used in the same session because they will not be stored in the server as database objects.
Since they need not store in the database, they need no compilation steps. They are written and executed
directly, and compilation and execution happen in a single process.
Below are few more characteristics of Anonymous blocks.
These blocks don't have any reference name specified for them.
These blocks start with the keyword 'DECLARE' or 'BEGIN'.
Since these blocks do not have any reference name, these cannot be stored for later purpose. They
shall be created and executed in the same session.
They can call the other named blocks, but call to anonymous block is not possible as it is not having
any reference.
It can have nested block in it which can be named or anonymous. It can also be nested in any blocks.
These blocks can have all three sections of the block, in which execution section is mandatory; the
other two sections are optional.
Named blocks/Subprograms:
A PL/SQL subprogram is a named PL/SQL block that can be invoked repeatedly. If the subprogram has
parameters, their values can differ for each invocation. A subprogram is either a procedure or a function.
Typically, you use a procedure to perform an action and a function to compute and return a value.
Named blocks have a specific and unique name for them. They are stored as the database objects in the
server. Since they are available as database objects, they can be referred to or used as long as it is present on
the server. The compilation process for named blocks happens separately while creating them as a database
objects.
Below are few more characteristics of Named blocks.
These blocks can be called from other blocks.
The block structure is same as an anonymous block, except it will never start with the keyword
'DECLARE'. Instead, it will start with the keyword 'CREATE' which instruct the compiler to create
it as a database object.
These blocks can be nested within other blocks. It can also contain nested blocks.
Named blocks are basically of two types:
1. Procedure
2. Function
Anonymous block
PL/SQL program units organize the code into blocks. A block without a name is known as an anonymous
block. The anonymous block is the simplest unit in PL/SQL. It is called anonymous block because it is not
saved in the Oracle database.
An anonymous block is an only one-time use and useful in certain situations such as creating test units. The
following illustrates anonymous block syntax:
[DECLARE]
Declaration statements;
BEGIN
Execution statements;
[EXCEPTION]
Exception handling statements;
END;
AnonymousBlocks
/
DECLARE(Optional)
Variables,Cursors,etc.
BEGIN(Mandatory)
SQLandPL/SQLCOMMANDS
EXCEPTION(Optional)
Exceptional_Handlingactions;
END;(Mandatory)
DECLARE
l_message
VARCHAR2(100):='HelloWorld!';
BEGIN
DBMS_OUTPUT.put_line(l_message);
END;
Named block accepts the mode of Parameter like in, out, inout
DECLARE or BEGIN.
7 The anonymous block statement is an executable statement that can contain PL/SQL control statements
and SQLStatements. It can be used to implement procedural logic in a scripting language.
Named block or stored procedure is a pl/sql block that oracle stores in the database and can be called by
name
From any application examples are function, procedure and packages, etc.
8. Anonymous block are created on client and subprograms are stored on server. It is possible to call
subprograms from anonymous block.
SUBPROGRAMSPROCEDURE
Create[OrReplace]procedurename[parameters]is|as
(Mandatory)
Variables,Cursors,etc(Optional)
BEGIN(Mandatory)
SQL&plsqlSTATEMENTS;
EXCEPTION(Optional)
WhenException_handlingactions;
END[NAME](Mandatory)
Example|of|namedblock
CREATEORREPLACEFUNCTIONFINDAREA(LENINNUMBER,WIDINNUMBER)
RETURNNUMBER
ASVAREANUMBER;
BEGIN
VAREA:=LEN*WID;
RETURNVAREA;
END;
-- %TYPE is used to declare a field with the same type as that of a specified table's column:
DECLARE
v_EmpName emp.ename%TYPE;
BEGIN
SELECT ename INTO v_EmpName FROM emp WHERE ROWNUM = 1;
DBMS_OUTPUT.PUT_LINE('Name = ' || v_EmpName);
END;
/
-- %ROWTYPE is used to declare a record with the same types as found in the specified database table,
view or cursor:
DECLARE
v_emp emp%ROWTYPE;
BEGIN
v_emp.empno := 10;
v_emp.ename := 'XXXXXXX';
END;
/
Records
A record is a data structure that can hold data items of different kinds. Records consist of different fields,
similar to a row of a database table.
* %type --- single column's datatype and size stored/assigned into one
variable
syntax : TABLENAME.COLUMNNAME%TYPE
* %rowtype --- all column's datatype and size stored in one variable
syntax : TABLENAME%ROWTYPE
* record --- multiple column's datatype and size stored in one variable
syntax : TYPE typename IS RECORD(variable1 datatype1,var2 dat2,...)
Conditional/Control statements
IF-THEN Statement
The IF-THEN statement is mainly used to execute a particular section of codes only when the condition is
satisfied.
The condition should yield Boolean (True/False). It is a basic conditional statement which will allow the
ORACLE to execute/skip a particular piece of code based on the pre-defined conditions.
Syntax for IF THEN Statements:
IF <condition: returns Boolean>
THEN
-executed only if the condition returns TRUE
<action_block>
END if;
In the above syntax, keyword 'IF' will be followed by a condition which evaluates to 'TRUE'/'FALSE'.
The control will execute the <action_block> only if the condition returns <TRUE>.
In the case of condition evaluates to <FALSE> then, SQL will skip the <action_block>, and it will start
executing the code next to 'END IF' block.
Note: Whenever condition evaluated to 'NULL', then SQL will treat 'NULL' as 'FALSE'.
Example1: To print a message when a number has value more than 100, we execute the following code.
DECLARE
a NUMBER :=10;
BEGIN
dbms_output.put_line(‘Program started.' );
IF( a > 100 ) THEN
dbms_output.put_line('a is greater than 100');
END IF;
dbms_output.put_line(‘Program completed.');
END;
/
Example2: we are going to print a message if a given alphabet is present in English vowels (A, E, I, O, U).
DECLARE
a CHAR(1) :=’u’;
BEGIN
IF UPPER(a) in ('A’,'E','I','0','U' )
THEN
dbms_output.put_line(‘The character is
in English Vowels');
END IF;
END;
/
IF-THEN-ELSE Statement
The IF-THEN-ELSE statement is mainly used to select between two alternatives based on the condition.
Syntax for IF-THEN-ELSE Statements:
IF <condition: returns Boolean>
THEN
-executed only if the condition returns TRUE
<action_blockl>
ELSE
-execute if the condition failed (returns FALSE)
<action_block2>
END if;
In the above syntax, keyword 'IF' will be followed by a condition which evaluates to 'TRUE'/'FALSE'.
The control will execute the <action_block1> only if the condition returns <TRUE>.
In case of condition evaluates to <FALSE> then, SQL will execute <action_block2>.
In any case, one of the two action blocks will be executed.
Note: Whenever condition evaluates to 'NULL', then SQL will treat 'NULL' as 'FALSE'.
Example 1: In this example, we are going to print message whether the given number is odd or even.
DECLARE
a NUMBER-11;
BEGIN
dbms_output.put_line (‘Program started');
IF( mod(a,2)=0) THEN
dbms_output.put_line('a is even number' );
ELSE
dbms_output.put_line('a is odd number1);
END IF;
dbms_output.put_line (‘Program completed.’);
END;
/