Date post: | 16-Jan-2015 |
Category: |
Education |
Upload: | atiqa-khan |
View: | 133 times |
Download: | 0 times |
June 18, 2011
Saturday, August 25, 2012
11
An Introduction to PL/SQL
Submitted to: Sir. Hassan
Submitted by: Atiqa Ijaz Khan
Roll no: SS09-03
BS (Hons.) 4th Semester
Department of the Space Sciences
University of the Punjab
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
2
TABLE OF CONTENTS
1. An introduction to the SQL………………………………………………………………03
a. Command…...............................................................................................................
................................................................................................................................03
b. Functions………………………………………………………………………........
................................................................................................................................04
2. An introduction to the PL/SQL…………………………………………………………..04
a. Advantages of the PL/SQL……………………………………………………....04
3. Operation on the PL/QL………………………………………………………………….05
a. PL/SQL Block structure………………………………………………………….06
b. PL/SQL Variables
structure……………………………………………………..................................09
c. PL/SQL Functions
structure…………………………………………………………………………..10
d. PL/SQL Procedures
structure……………………..……………………………………………………12
e. PL/SQL IF structure……..……………………………………………………….13
f. PL/SQL Case
structure……………….………………………………………………………….14
g. PL/SQL Loop structure,………………………………………………………….16
h. PL/SQL While
structure…………………………………………………………………..………17
i. PL/SQL For structure…………………………………………………….………18
j. PL/SQL Cursors structure……………………………………………….……….19
4. PL/SQL engine………………………………….………………………………………..20
5. Character
set……………………………………………….…….….………………………………21
6. Important definitions………………………………………………………………….….21
7. References……………………………………………………………………….…….…25
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
3
An Introduction to the SQL
SQL stands for “Structured Query Language” and can be pronounced as “SQL” or “sequel –
(Structured English Query Language)”. It is a query language used for accessing and modifying
information in the database.
SQL Commands:
Few of the sql commands used in sql programming are:
1. SELECT Statement,
2. UPDATE Statement,
3. INSERT INTO Statement,
4. DELETE Statement,
5. WHERE Clause,
6. ORDER BY Clause,
7. GROUP BY Clause,
8. ORDER Clause,
9. Joins,
10. Views,
11. GROUP Functions,
12. Indexes.
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
4
SQL Functions:
In a simple manner, SQL is a non-procedural, English-like language that processes data in
groups of records rather than one record at a time. Few functions of SQL are:
1. store data
2. modify data
3. retrieve data
4. modify data
5. delete data
6. create tables and other database objects
7. delete data
An introduction to the PL/SQL:
PL/SQL stands for “Procedural Language extensions to the Structured Query Language or
SQL.” SQL is the powerful tool for both querying and update data in relational databases.
Oracle introduced PL/SQL to extend some limitations of SQL to provide a more
comprehensive solution for building mission-critical applications running on Oracle
database.
Advantages of PL/SQL:
PL/SQL is a completely portable, high-performance transaction processing language that
offers the following advantages:
1. Tight Integration with SQL
2. Better Performance
3. Higher Productivity
4. Full Portability
5. Tight Security
6. Access to Pre-defined Packages
7. Support for Object-Oriented Programming
8. Support for Developing Web Applications and Pages
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
5
Pl/SQL is a part of RDBMS that resides on:
Operation on PL/SQL
Some of the operations on PL/SQL are listed below:
Server
Client
PL/SQL
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
6
a. PL/SQL block structure: PL/SQL is a block-structured language. The PL/SQL block
allows you to reflect that logical structure in the physical design of your programs.
Sections of the block:
There is a common block structure to all the different types of modules. The block is broken
up into four different sections, as follows:
Header: Relevant for named blocks only, the header determines the way that the
named block or program must be called. The header includes the name, parameter
list, and RETURN clause (for a function only).
Declaration section: The part of the block that declares variables, cursors, and sub-
blocks that are referenced in the execution and exception sections. The declaration
section is optional, but if you have one, it must come before the execution and
exception sections.
Execution section: The part of the PL/SQL blocks containing the executable
statements, the code that is executed by the PL/SQL run-time engine. The execution
section contains the IF-THEN-ELSEs, LOOPs, assignments, and calls to other
PL/SQL blocks. Every block must have at least one executable statement in the
execution section.
Exception section: The section that handles exceptions to normal processing
(warnings and error conditions). This final section is optional. If it is included,
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
7
control is transferred to this section when an error is encountered. This section then
either handles the error or passes control to the block that called the current block.
Anonymous block:
PL/SQL program units organize the code into blocks. A block without name is known as
anonymous block. The anonymous block is the simplest unit in PL/SQL. It is called
anonymous block because it is not saved in the database. The anonymous blocks are only
one-time use and useful in certain situations such as creating test units. The following
illustrates anonymous block syntax:
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
8
Block
Named Stored
Can be refered
Anonymous Cant be sored and refered
[Declare]
Declare statement;
Begin
Execution statement;
[Exception]
Exception handling
statment;
END:
/
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
9
b. PL/SQL variables:
In PL/SQL, a variable is a meaningful name of a temporary storage location that supports a
particular data type in program.
PL/SQL Variable Naming Convention:
Like other programming languages, a variable in PL/SQL must follow the naming rules as
below:
1. The variable name must be less than 31 characters. Try to make it as meaningful as
possible within 31 characters.
2. The starting of a variable must be an ASCII letter. It can be either lowercase or
uppercase. Note that PL/SQL is not case-sensitive.
3. A variable name can contain numbers, underscore, and dollar sign characters
followed by the first character. Again, do not make your variables hard to read and
understand to make it easier to maintain in the future.
It is recommended that you should follow the naming conventions in the table 1.1 below to
name variables to make it obvious in PL/SQL programs:
Prefix Data Type
v_ VARCHAR2
n_ NUMBER
t_ TABLE
r_ ROW
d_ DATE
b_ BOOLEAN
For example, if you want to declare a variable to hold the first name of employee with the
data type VARCHAR2 the variable name should be v_first_name.
PL/SQL Variable Declaration:
To declare a variable, you type a variable name followed by the data type and terminated by
a semicolon (;). You can also explicitly add length constraint to the data type in a set of
parentheses. Here is an example of declaring some variables in an anonymous
block:PL/SQL code.
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
10
c. PL/SQL functions:
PL/SQL function is a named block that returns a value. PL/SQL functions are also known as
subroutines or subprograms.
DECLARE
v_first_name VARCHAR2(20);
v_last_name VARCHAR2(20);
n_employee_id NUMBER;
d_hire_date DATE;
BEGIN
NULL;
END;
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
11
Syntax Explaination:
1. The {function_name} is the name of the function. Function name should start with a
verb for example function convert_to_number.
2. {parameter_name} is the name of parameter being passed to function along with
parameter’s data type {parameter_data_type}. There are three modes for parameters:
IN, OUT and IN OUT.
3. The IN mode is the default mode. You use the IN mode when you want the formal
parameter is read-only. It means you cannot alter its value in the function. The IN
parameter behaves like a constant inside the function. You can assign default value
to the IN parameter or make it optional.
4. The OUT parameters return values to the caller of a subprogram. An OUT parameter
cannot be assigned a default value therefore you cannot make it optional. You need
to assign values to the OUT parameter before exiting the function or its value will be
NULL. From the caller subprogram, you must pass a variable to the OUT parameter.
CREATE [OR REPLACE] FUNCTION
{function_name} [(
{parameter_1} [IN] [OUT] {parameter_data_type_1},
{parameter_2} [IN] [OUT]
{parameter_data_type_2},...
{parameter_N} [IN] [OUT] {parameter_data_type_N}
)]
RETURN {return_datatype} IS
--the declaration statements
BEGIN
-- the executable statements
RETURN {return_data_type};
EXCEPTION
-- the exception-handling statements
END;
/
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
12
5. In the IN OUT mode, the actual parameter is passed to the function with initial
values. And then inside the function, the new value is set for the IN OUT parameter
and returned to the caller. The actual parameter must be a variable.
6. The function must have at least one RETURN statement in the execution part. The
RETURN clause in the function header specifies the data type of returned value.
NOTE:
The block structure of a function is the same as an anonymous block except for the addition
CREATE [OR REPLACE] FUNCTION, the parameters section, and a RETURN clause.
d. PL/SQL Procedure:
A PL/SQL procedure is a named block that performs one or more actions. PL/SQL
procedure allows you to wrap complex business logic and reuse it. The following illustrates
the PL/SQL procedure’s syntax:PL/SQL .
PROCEDURE [schema.]name[( parameter[,
parameter...] ) ]
[AUTHID DEFINER | CURRENT_USER]
IS
[--declarations statements]
BEGIN
--executable statements
[ EXCEPTION
---exception handlers]
END [name];
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
13
Syntax Explanation:
The PL/SQL procedure can be divided into two sections: header and body.
PL/SQL Procedure’s Header
The section before the keyword IS called procedures’ header or procedure’s signature. The
elements in the procedure’s header are listed as follows:
Schema: The optional name of the schema that own this procedure. The default is
the current user. If you specify a different user, the current user must have privileges
to create a procedure in that schema.
Name: The name of the procedure. The name of the procedure like a function
should be always meaningful and starting by a verb.
Parameters: The optional list of parameters. Please refer to the PL/SQL function for
more information on parameter with different modes IN, OUT and IN OUT.
AUTHID: The optional AUHTID determines whether the procedure will execute
with the privileges of the owner (DEFINER) of the procedure or the current user
(CURRENT_USER).
PL/SQL Procedure’s Body
Everything after the keyword IS known as procedure’s body. The procedure’s body consists
of declaration, execution and exception sections. The declaration and exception sections are
optional. You must have at least one executable statement in the execution section. The
execution section is where you put the code to implement a given business logic to perform
one or more tasks.
In PL/SQL procedure you still have RETURN statement. However unlike the RETURN
statement in function that returns a value to calling program, RETURN statement in
procedure is used only to halt the execution of procedure and return control to the caller.
RETURN statement in procedure does not take any expression or constant.
e. PL/SQL IF statements:
The PL/SQL IF statement allows you to execute a sequence of statements conditionally. The
IF statements evaluate a condition. The condition can be anything that evaluates to a logical
true or false such as comparison expression or combination of multiple comparison
expressions. You can compare two variables of the same type or different types but they are
convertible to each other. You can compare two literals. In addition, a Boolean variable can
be used as a condition.
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
14
Forms of pl/sql IF statements:
The PL/SQL IF statement has three forms:
1. IF-THEN,
2. IF-THEN-ELSE
3. IF-THEN-ELSIF.
Syntax:
The following illustrates the IF-THEN statement:PL/SQL IF-THEN Statement
NOTE:
This is the simplest form of the IF statement. If the condition evaluates to true, the sequence
of statements will execute. If the condition is false or NULL, the IF statement does nothing.
Note that END IF is used to close the IF statement, not ENDIF.
f. PL/SQL case statement:
He PL/SQL CASE statement allows you to execute a sequence of statements based on a
selector. A selector can be anything such as variable, function, or expression that the CASE
statement evaluates to a Boolean value. You can use almost any PL/SQL data types as a
selector except BLOB, BFILE and composite types. Unlike the PL/SQL IF statement,
PL/SQL CASE statement uses a selector instead of combination of multiple Boolean
expressions. The following illustrates the PL/SQL CASE statement syntax:PL/SQL CASE
Statement Syntax
IF condition THEN
sequence_of_statements;
END IF;
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
15
Followed by the keyword CASE is a selector. The PL/SQL CASE statement evaluates the
selector only once to decide which sequence of statements to execute. Followed by the
selector is any number of the WHEN clause. If the selector value is equal to expression in
the WHEN clause, the corresponding sequence of statement after the THEN keyword will
be executed. If the selector’s value is not one of the choices covered by WHEN clause, the
sequence of statements in the ELSE clause is executed. The ELSE clause is optional so if
you omit the ESLE clause, PL/SQL will add the following implicit ELSE clause:PL/SQL
code
ELSE RAISE CASE_NOT_FOUND;
If you use implicit ELSE clause in the PL/SQL CASE statement, exception
CASE_NOT_FOUND is raised and can be handled in the exception handling part of the
PL/SQL block as usual.
The keywords END CASE are used to terminate the CASE statement.
[<<label_name>>]
CASE [TRUE | selector]
WHEN expression1 THEN
sequence_of_statements1;
WHEN expression2 THEN
sequence_of_statements2;
...
WHEN expressionN THEN
sequence_of_statementsN;
[ELSE sequence_of_statementsN+1;]
END CASE [label_name];
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
16
g. PL/SQL loop statements:
PL/SQL LOOP is an iterative control structure that allows you to execute a sequence of
statements repeatedly. The simplest of LOOP consists of the LOOP keyword, the sequence
of statements and the END LOOP keywords, as shown below:PL/SQL LOOP Statement
Note that there must be at least one executable statement between LOOP and END LOOP
keywords. The sequence of statements is executed repeatedly until it reaches a loop exits.
PL/SQL provides you EXIT and EXIT-WHEN statements to allow you to terminate a loop.
1. The EXIT forces the loop halt execution unconditionally and passes control to the
next statement after keyword END LOOP.
2. The EXIT-WHEN statement allows the loop complete conditionally. When the
EXIT-WHEN statement is reached, the condition in the WHEN clause is checked. If
the condition is true, the loop is terminated and pass control to the next statement
after keyword END LOOP. If condition is false, the loop will continue repeatedly
until the condition is evaluated to true. Therefore if you don’t want to have a infinite
loop you must change variable’s value inside loop to make condition true.
LOOP
sequence_of_statements;
END LOOP;
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
17
h. PL/SQL while stamen:
In some programming contexts, you don’t know in advance how many times to execute a
sequence of statements because the execution depends on a condition that is not fixed. In
such cases, you should you PL/SQL WHILE loop statement. The following illustrates the
PL/SQL WHILE LOOP syntax:
PL/SQL WHILE Loop Syntax is:
A condition is a Boolean variable or expression that values to Boolean values of TRUE,
FALSE or NULL. Each time before executing the sequence of statements, the condition is
checked. If the condition is evaluated to TRUE, then the sequence of statements is executed.
If it evaluates to FALSE or NULL, the loop terminates and control passes to the next
executable statement following the END LOOP keywords. It is important to note that the
sequence of statements may not execute even a single time based on condition. In addition,
inside the loop you have to change values of variables to make the condition is FALSE or
NULL to terminate the loop or you will have an endless loop. The PL/SQL WHILE loop is
effective when you don’t know how many times the loop will execute. If the loop runs for a
specific number of times, you should use the PL/SQL FOR loop statement instead.
WHILE condition
LOOP
sequence_of_statements;
END LOOP;
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
18
i. PL/SQL for statement:
PL/SQL FOR loop is an iterative statement that allows you to execute a sequence of
statements a fixed number of times. Unlike the PL/SQL WHILE loop, the number of
iterations of the PL/SQL FOR loop is known before the loop starts. The following illustrates
the PL/SQL FOR loop statement syntax:PL/SQL FOR Loop Syntax
Let’s examine the PL/SQL FOR loop syntax in details:
1. loop_counter. The PL/SQL automatically creates a local variable loop_counter with
data type INTEGER implicitly in the FOR loop so you don’t have to declare it. The
scope of the loop_counter variable is within the loop itself so you cannot reference it
outside the loop. After each iteration, PL/SQL increases loop_counter by 1 and
checks if the loop_counter is still in the range of lower_bound and higher_bound to
execute the next iteration. If the loop_counter is not in the range, the loop terminates.
2. The lower_bound..higher_bound is the range of integers that FOR loop iterates over.
This range is known as iteration scheme. The range operator is specified by a double
dot (..) between lower_bound and higher_bound. The FOR loop evaluates the range
when the loop first entered and never re-evaluated. The lower_bound has to be less
than or equal to the higher_bound. If the lower_bound is equal to the higher_bound,
the sequence of statements is executed once. If the lower_bound is larger than the
higher_bound, the sequence within the loop will never execute. The lower_bound
and higher_bound can be literals, variables, or expressions that evaluate to numbers.
Otherwise, PL/SQL raises VALUE_ERROR exception.
FOR loop_counter IN [REVERSE] lower_bound ..
higher_bound
LOOP
sequence_of_statements;
END LOOP;
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
19
3. By default, the loop iterates in the upward fashion from the lower_bound to the
higher_bound. However, if you want to force the loop to iterates in a downward way
from the higher_bound to the lower_bound, you can use the REVERSE keyword
after the IN keyword.
NOTE: You must have at least one executable statement between LOOP and END
LOOP keywords.
j. PL/SQL cursors:
A cursor is a temporary work area created in the system memory when a SQL statement
is executed. A cursor contains information on a select statement and the rows of data
accessed by it. This temporary work area is used to store the data retrieved from the
database, and manipulate this data. A cursor can hold more than one row, but can
process only one row at a time. The set of rows the cursor holds is called the active set.
Types of the Cursors:
There are two types of cursors in PL/SQL:
1. Implicit cursors: These are created by default when DML statements like,
INSERT, UPDATE, and DELETE statements are executed. They are also
created when a SELECT statement that returns just one row is executed.
2. Explicit cursors: They must be created when you are executing a SELECT
statement that returns more than one row. Even though the cursor stores multiple
records, only one record can be processed at a time, which is called as current
row. When you fetch a row the current row position moves to next row.
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
20
Steps to explicit cursor:
There are four steps in using an Explicit Cursor.
1. DECLARE the cursor in the declaration section.
2. OPEN the cursor in the Execution Section.
3. FETCH the data from cursor into PL/SQL variables or records in the Execution
Section.
4. CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
NOTE: Both implicit and explicit cursors have the same functionality, but they differ in the
way they are accessed.
PL/SQL engine:
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored
in the client system (client-side) or in the database (server-side).
Server
passed on the oracle server
Client
Proceeds on client side
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
21
Character Set for PL/SQL:
They are as follows:
1. Letter(A-Z, a-z)
2. Digits(0-9)
3. Specific symbols (@, #, $, %)
Important definitions:
1. Begin…end:
Executable commands section always starts and ends with a keyword of
BEGIN and END respectively.
2. Nested Blocks:
When PL/SQL programs holds more than one declaration sections with more
than one begin and end.
3. DBMS_OUTPUT>PUT_LINE:
This allows displaying of messages and variables values on console.
4. Constant:
Its value does not change at the run time.
5. Literal:
It just works like a constant.
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
22
6. %ROW Type:
It’s a variable may also have a type that is record with several fields.
7. Assignment:
It is used to assigns a value to a variable.
8. Operator:
It work on data items and performs some mathematical and logical calculations
and changes data.
• 100
• NULL
Numeric
• Hello
• Word
String
• True
• False
Boolean
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
23
9. Comments:
It does not affect the SQL statements execution.
Arithematic
• +,-
• *, /
Relational
• =>
• <
Logical
• And
• Or
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
24
10. Data types:
Identify the type of the data.
11. Identifiers:
It refers to the name for PL/SQL objects.
12. Reserved word:
It is per-defined for the per-decided purposes.
13. Delimiters:
They are the symbols with special meanings. They are used to separate one
unit/information/code from another.
• Point the other i.e.poniters, cursors.
•Holds location of the objects.
•Made of the other types i.e. record, VARRAY.
•Does not made up of the other types.i.e. varchar, boolean.
Scalar Composite
Refernce Large
objects(LOB)
Department of the Space Sciences
B.S(Hons.) 4th Semester
Pa
ge
25
References:
1. www.aiken.isy.vcu.edu ………………………………………………………….18-
02-11
2. www.beginner-sql-tutorial.com …………………………………………………17-
06-11
3. www.mik.ua ……………………………………………………………………..17-
06-11
4. www.nature.bios.com ……………………………………………………………18-
06-11
5. www.oracle.com ………………………………………………………………...18-
06-11
6. Oracle database 11g PL/SQL programming……………………………………..17-
06-11
7. www.plsql.tutorial.com …………………………………………………………18-
06-11
8. www.plsqltutorial.info …………………………………………………………..17-
06-11
9. www.slideworld.com ……………………………………………………………18-
06-11
10. www.sqltutorial.org ……………………………………………………………..17-
06-11