Você está na página 1de 10

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.

What is PLSQL and its use?


Portions of applications: PL/SQL program units can return a set of values (functions), or PL/SQL routines
can perform database operations (procedures). These functions and procedures may be called by other
functions and procedures or (in the case of functions) used in SQL statements.

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 is a completely portable, high-performance transaction-processing language.

 PL/SQL provides a built-in, interpreted and OS independent programming environment.

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

 PL/SQL is tightly integrated with SQL.


 It offers extensive error checking.
 It offers numerous data types.
 It offers a variety of programming structures.
 It supports structured programming through functions and procedures.
 It supports object-oriented programming.
 It supports the development of web applications and server pages.
Advantages of PL/SQL
PL/SQL has the following advantages −

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

 Applications written in PL/SQL are fully portable.

 PL/SQL provides high security level.

 PL/SQL provides access to predefined SQL packages.

 PL/SQL provides support for Object-Oriented Programming.

 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

The PL/SQL architecture mainly consists of following three components:

1. PL/SQL block
2. PL/SQL Engine
3. Database Server

PL/SQL block:

 This is the component which has the actual PL/SQL code.


 This consists of different sections to divide the code logically (declarative section for declaring
purpose, execution section for processing statements, exception handling section for handling errors)
 It also contains the SQL instruction that used to interact with the database server.
 All the PL/SQL units are treated as PL/SQL blocks, and this is the starting stage of the architecture
which serves as the primary input.
 Following are the different type of PL/SQL units.
o Anonymous Block
o Function
o Library
o Procedure
o Package Body
o Package Specification
o Trigger
o Type
o Type Body

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.

Advantage of Using PL/SQL

1. Better performance, as SQL is executed in bulk rather than a single statement


2. High Productivity
3. Tight integration with SQL
4. Full Portability
5. Tight Security
6. Support Object Oriented Programming concepts.

D/B SQL and PLSQL


 SQL is a Structured Query Language used to issue a single query or execute a single insert/update/delete.
PL-SQL is a programming language SQL, used to write full programs using variables, loops, operators etc. to carry out
multiple selects/inserts/updates/deletes.
 SQL may be considered as the source of data for our reports, web pages and screens.
PL/SQL can be considered as the application language similar to Java or PHP. It might be the language used to build,
format and display those reports, web pages and screens.
 SQL is a data oriented language used to select and manipulate sets of data.
PL/SQL is a procedural language used to create applications.
 SQL is used to write queries, DDL and DML statements.
PL/SQL is used to write program blocks, functions, procedures triggers, and packages.
 SQL is executed one statement at a time.
PL/SQL is executed as a block of code.
 SQL is declarative, i.e., it tells the database what to do but not how to do it.
Whereas, PL/SQL is procedural, i.e., it tells the database how to do things.
 SQL can be embedded within a PL/SQL program.
But PL/SQL can’t be embedded within a SQL statement.

PLSQL ( Procedural language structured query language)

why ?

To implement the business logic into technical

To reduce the network traffic

begin

null;

end;

basic PLSQL structure :

BEGIN
-----MIN one statement

END;

Notes : oracle will read line by line from begin

dbms_output.put_line ---> to print the value in plsql

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;

notes : only one argument is possible in dbms_output

cmd : set serveroutput on

toad : dbms_output tab(enable)

PL/SQL Block Structure


The anonymous block has three basic sections that are the declaration, execution, and exception handling.
Only the execution section is mandatory and the others are optional.
The declaration section allows you to define data types, structures, and variables. You often declare
variables in the declaration section by giving them names, data types, and initial values.
The execution section is required in a block structure and it must have at least one statement. The execution
section is the place where you put the execution code or business logic code. You can use both procedural
and SQL statements inside the execution section.
The exception handling section is starting with the EXCEPTION keyword. The exception section is the
place that you put the code to handle exceptions. You can either catch or handle exceptions in the exception
section.

What is PL/SQL block?


In PL/SQL, the code is not executed in single line format, but it is always executed by grouping the code
into a single element called Blocks. Blocks contain both PL/SQL as well as SQL instruction. All these
instruction will be executed as a whole rather than executing a single instruction at a time.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are different sections
of PL/SQL blocks.

Below is the syntax of the PL/SQL block structure.

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;

Differences between Anonymous Blocks and Subprograms

1. Anonymous is unnamed plsql block

A stored procedure or a named block is a pl/sql black.

2. Anonymous cannot save in database,

Oracle stores pl/sql block in the database.

3. We cannot call Anonymous blocks.

We can recall named block whenever program requires it.

4. Anonymous Black cannot allow any mode of parameter.

Named block accepts the mode of Parameter like in, out, inout

5 Anonymous blocks are to be compiled each time when we require it.


But once we compile a named pl/sql block it is permanently stored as P-code after compilation in the

Shared pool of the system global area.

6. Anonymous block: Starts with

DECLARE or BEGIN.

Named block: Starts with Header Block.

Like name of block, type of block, parameter.

Named Black has NAME: like PROCEDURE, FUNCTION, and PACKAGES

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.

9. Anonymous blocks do not return values.

Subprograms called functions must return values.

10. Anonymous blocks cannot take parameters.

Subprograms can take parameters.

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;

E.g SELECT FIND_AREA(25,15) AREA FROM DUAL;


Difference between % type and %rowtype in oracle
%type vs %rowtype
1. %type provides the data type of a variable or a database column to that variable.
2. %rowtype provides the record type that represents a entire row of a table or view or columns selected in
the cursor.

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

PL/SQL can handle the following types of records −


 Table-based
 Cursor-based records
 User-defined records

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

Você também pode gostar