PLsql
PLsql
1
Advantages of using PL/SQL to
access Oracle
• PL/SQL is managed centrally within the
database
• Code is managed by the DBA and execution
privileges are managed in the same way as with
other objects
• PL/SQL objects are first-class Oracle DB objects
• Easy to read
– With modularity features and error handling
DIFFERENCE BETWEEN PL/SQL AND SQL
• When a SQL statement is issued on the client
computer, the request is made to the database on the
server, and the result set is sent back to the client.
• As a result, a single SQL statement causes two trips on
the network. If multiple SELECT statements are issued,
the network traffic increase significantly very fast. For
example, four SELECT statements cause eight network
trips.
• If these statements are part of the PL/SQL block, they
are sent to the server as a single unit. The SQL
statements in this PL/SQL program are executed at the
server and the result set is sent back as a single unit.
There is still only one network trip made as is in case of
a single SELECT statement.
Comparison of SQL and PL/SQL
Terms to know
PL/SQL (Procedure Language/SQL)
Stored procedure
Function (user-defined function or UDF)
SQL vs. PL/SQL
• As we have learned, one benefit of SQL is that it is
declarative, allowing us to easily create Oracle
database tables and write queries to insert, update,
delete, and view records without specifying too much
detailed data manipulation steps.
8
• SQL is not a procedural language but a declarative language.
• Using SQL, we carefully phrase what we want and then let the
DBMS get it for us.
9
Why SQL is declarative not procedural?
10
End user vs. programmer
• In run time, the end users provide input data and interpret
output, but the logic needs to be implemented in the design time
in the program which should have been done by programmers.
11
PL/SQL
• PL/SQL is the Oracle solution to this need,
– PL/SQL stands for Procedural Language/SQL.
– PL/SQL extends SQL by adding constructs found in procedural
languages, resulting in a structural language that is more powerful
than SQL.
– A procedural programming language that pure oracle applications
uses to manipulate database data.
– A complement to SQL.
– An extension to SQL, allowing us do things we cannot do in SQL
alone.
12
Good things combined
• A PL/SQL program combines good things from both sides, combining
SQL quries with procedural commands for tasks such as
– manipulating variable values,
– Evaluating IF/THEN decision control structures,
– Creating loop structures that repeat instructions multiple times until the loop
reaches an exit condition.
– Build in functions
– User defined functions
13
• A Full-featured procedural programming language
• An interpreted language, which means that a program called the
PL/SQL interpreter checks each program command for syntax
errors, translates each command into machine language, and
then executes each program command, one command at a
time.
• PL/SQL commands are not case-sensitive, except for character
strings, which you must enclose in single quotation marks.
• The PL/SQL interpreter ignores blank spaces and line breaks.
• A semicolon (;) marks the end of each PL/SQL command.
• The programming style is a mixture of conventional statements
(if, while, etc.) and SQL statements.
14
15
PL/SQL Variables and Data Types
• Variable names must follow the Oracle naming standard (Example:
current_s_id, not $current_s_id)
• Strongly typed language
– Explicitly declare each variable including data
type before using variable
• Variable declaration syntax:
variable_name
data_type_declaration;
• Default value always NULL
16
Scalar Variables
• Reference single value such as number, date, string
• Data types correspond to Oracle 10g database data types
– VARCHAR2
– CHAR
– DATE
– NUMBER
17
Composite Variables
• Data object made up of multiple individual data elements
• Data structure contains multiple scalar variables
• Composite variable data types include:
– RECORD (multiple scalar values similar to a table’s
record)
A
R
– TABLE (tabular structure with multiple columns
R and rows)
A
Y – VARRAY (variable-sized array. Tabular
structure that can expand or contract based on
data values)
18
Reference Variables
• Directly reference specific database column or row
• Assume data type of associated column or row
• %TYPE data declaration syntax:
variable_name tablename.fieldname
%TYPE;
• %ROWTYPE data declaration syntax:
variable_name tablename%ROWTYPE;
20
Variables
• Variables
– Used to store numbers, character strings, dates, and
other data values
– Avoid using keywords, table names and column names
as variable names
– Must be declared with data type before use:
variable_name data_type_declaration;
• Userid varchar2(10);
– Default value is always NULL when declared without
being initialized.
• The initial value of any variable, regardless of its type,
is NULL.
21
Some simple statements
• Return
• Goto <label>
• Exit, break a loop
22
Arithmetic Operators in PL/SQL
Operator Description
** Exponentiation
* Multiplication
/ Division
+ and - Addition and subtraction
- negation
23
Most SQL Relational Operators
can be used for PL/SQL
= equal to all =X
24
Logical Operators
25
Expressions
• Simple arithmetic expressions
• Simple relational expressions
• Simple logical expressions
• Nested and compound expressions
26
Built-in functions
• You can also you built-in functions to perform common tasks
such as manipulating numbers or character strings.
27
PL/SQL Data Conversion
Functions
28
A PL/SQL block
• The header section
• Declaration section, optional
• Execution section
• Optional exception section
29
PL/SQL Program Blocks
30
The scope of A PL/SQL block
for local variables
• A PL/SQL block establishes a scope for all locally-declared
variables.
• Outside of the block, those variables do not exist.
31
Executing a PL/SQL
Program in SQL*Plus
32
How to test out the PL/SQL program?
33
Debugging PL/SQL Programs
• Syntax error:
– Command does not follow the guidelines of the
programming language
– Generates compiler or interpreter error messages
• Logic error:
– Program runs but results in an incorrect result
– Caused by mistakes at semantic level in
programing
34
Finding and Fixing Syntax Errors
35
Finding and Fixing Logic Errors
36
PL/SQL Control Structures
Categories
• Conditional Control
• Iterative Control
• Sequential Control
38
Categories of control structure
1. Conditional
• Use IF/ELSIF to evaluate many conditions:
– IF condition1 THEN
commands that execute if condition1 is TRUE;
ELSIF condition2 THEN
commands that execute if condition2 is TRUE;
ELSIF condition3 THEN
commands that execute if condition3 is TRUE;
...
ELSE
commands that execute if none of the
conditions are TRUE;
END IF;
1. Sequential
39
PL/SQL Decision Control
Structures
• One way branch!
– We also say the commands are conditioned.
• Use IF/THEN structure to execute code if condition is true.
– IF condition THEN
commands that execute if condition is TRUE;
END IF;
• If condition evaluates to NULL it is considered false
40
Two way decision
41
Categories Contd..
2. Iterative Loops:
1. Simple loop
Syntax:
Loop
<Sequence of statements>
End loop;
2.WHILE<condition>
LOOP
<action>
End loop;
42
3. For loop
Syntax:
FOR variable IN [REVERSE] start ..end
LOOP
<action>
END LOOP;
43
Categories cont..
3. Sequential Control
Syntax:
GOTO <code block name>;
44
IF/ELSIF Example
45
Complex Conditions
• Created with logical operators AND, OR and NOT
• AND is evaluated before OR
• Use () to set precedence
46
Cursors
48
Types of Cursors
49
Implicit Cursor
50
Explicit Cursor
52
Implicit Cursor
53
Using an Implicit Cursor
54
Loop in Implicit Cursor
55
• The select statement that finds the total number of employee is
a simple select statement with added keyword INTO. The INTO
part of the statement is required in order to put the values
returned by the select statement into the corresponding PL/SQL
variables.
56
Explicit Cursor
57
Cursor
• In its simplest form, you can think of a cursor as a pointer into a relation in the
database or dynamically generated from other relations.
• For example, the following cursor declaration associates the entire employee
table with the cursor named employee_cur:
– Step 1: cursor declaration
CURSOR employee_cur
IS
SELECT * FROM employee;
– Step 2: Once you have declared the cursor, you can open it:
OPEN employee_cur;
– Step 3: And then you can fetch data from it row by row, usually inside a loop
FETCH employee_cur INTO employee_rec;
In this case, each record fetched from this cursor represents an
entire record in the employee table.
– Step 4: finally, You can close the cursor:
CLOSE employee_cur;
58
Using an Explicit Cursor
• Declare the cursor
– CURSOR cursor_name IS select_query;
• Open the cursor
– OPEN cursor_name;
• Fetch the data rows
– LOOP
FETCH cursor_name INTO variable_name(s);
EXIT WHEN cursor_name%NOTFOUND;
• Close the cursor
– CLOSE cursor_name;
59
Cursor FOR Loop
60
Example
DECLARE
s_rollNo students.rollNo%type;
s_name students.name%type;
s_address students.address%type;
CURSOR cur_students is
SELECT rollNo, name, address
FROM students;
BEGIN
OPEN cur_students;
LOOP
FETCH cur_students into s_rollNo, s_name, s_address;
EXIT WHEN cur_students%notfound;
dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' || s_address);
END LOOP;
CLOSE cur_students;
END;
/
61
Summary
• PL/SQL is a programming language for working with an
Oracle database
• Scalar, composite and reference variables can be used
• The IF/THEN/ELSE decision control structure allows
branching logic
• Cursors are returned from queries and can be explicitly
iterated over
• Exception handling is performed in the exception
section. User defined exceptions help to enforce
business logic
62