0% found this document useful (0 votes)
3 views

PLsql

The document provides an introduction to PL/SQL, highlighting its advantages over SQL, such as centralized management and procedural capabilities. It explains the differences between SQL and PL/SQL, emphasizing PL/SQL's ability to handle multiple SQL statements in a single network trip. Additionally, it covers essential concepts like PL/SQL program blocks, variables, control structures, and cursors, illustrating how PL/SQL combines the strengths of both procedural and declarative programming.

Uploaded by

DRISHTI RAI
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PLsql

The document provides an introduction to PL/SQL, highlighting its advantages over SQL, such as centralized management and procedural capabilities. It explains the differences between SQL and PL/SQL, emphasizing PL/SQL's ability to handle multiple SQL statements in a single network trip. Additionally, it covers essential concepts like PL/SQL program blocks, variables, control structures, and cursors, illustrating how PL/SQL combines the strengths of both procedural and declarative programming.

Uploaded by

DRISHTI RAI
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

Introduction to PL/SQL

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.

• The weakness for SQL is also due to its declarative


language feature: it has no support for procedural
constructs such as flow control, or loop mechanisms,
etc.
.
7
Procedural vs. declarative
• Procedural programming requires that the programmer tells how to
process data using detailed sequential or flow control instructions to.
– Bad: Procedural languages result in many lines of code.
– Good: Have more control on detail
• Declarative programming requires the programmer to tell what data
is needed.
– Good: The Declarative languages usually result in one statement of the
desired result.
– Bad: Have less control on data.

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.

• You write a single SQL declaration and hand it to the DBMS.


The DBMS then executes internal code, which is hidden from
us.

9
Why SQL is declarative not procedural?

• SQL came into existence as a relational database query


language.
• SQL was designed, evolved, optimized for structured data, i.e.
table, manipulation, saving people from considering tedious step
by step instructions.
• Being declarative is exactly what we want when it comes to data
manipulation.

• Not optimized nor designed for logics.

10
End user vs. programmer

• But the terminal user is not necessarily a programmer.


• Most database users, reasonably assumed to have no
programming knowledge at all, don’t use SQL commands or
SQLPLUS to interact with a database. Instead, users use GUI
frontend interface to deal with backend database.

• 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

• PL/SQL has other data types that do not correspond to


database data types

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;

LOB Data Type


• Must be manipulated using programs in
DBMS_LOB package 19
PL/SQL Program Blocks
• Declaration section
• Execution section
– Required
• Exception section
– Optional
• Comment statements
Enclosed within /* and */ for
several lines’ comments
-- for single line comments/* Script: Student register
Purpose: to enroll students in
class */

-- Script: Student register


-- Purpose: to enroll students

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

Query Relational Operators


Operator Meaning Data Type Pattern

= equal to all =X

> greater than all >X

< less than all <X

>= greater than or equal to all >=X

<= less than or equal to all <=X

<> or != not equal to all <>X

* wildcard Character *X, X*, *X*

? single-character wildcard Character ?X, X?, ?X?, X??

24
Logical Operators

• and, or, not

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

The built-in function SYSDATE returns a DATE value


containing the current date and time on your system.

32
How to test out the PL/SQL program?

• Create program in text editor


• Paste into SQL*Plus window
• Press Enter, type / then enter to execute.
– The forward slash (/) tells SQL*PLUS to go ahead
and process the commands in the 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

• Interpreter flags the line number and


character location of syntax errors
• If error message appears and the flagged line
appears correct, the error usually occurs on
program lines preceding the flagged line
• Comment out program lines to look for hidden
errors
• One error (such as missing semicolon) may
cause more – fix one error at a time

35
Finding and Fixing Logic Errors

• Locate logic errors by viewing variable values


during program execution
• There is no SQL*Plus debugger
• Use DBMS_OUTPUT statements to print
variable values

36
PL/SQL Control Structures

• PL/SQL allows you to branch and create loops


and function calls in the way that you have been
doing in C++/Java.
• If statement
• Loops: three different iteration constructs.
– Loop
– While
– For
– ..
37
Control Structure

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

• Use IF/THEN/ELSE to execute code if condition is


true or false
– IF condition THEN
commands that execute if condition is TRUE;
ELSE
commands that execute if condition is FALSE;
END IF;
• Can be nested – be sure to end nested statements

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

• Cursor is a temporary work area created in


system memory when a SQL statement is
executed.
• A cursor is a set of rows together with a pointer
that identifies a current row. It is a database
object to retrieve data from a result set one row
at a time.
• It is useful when we want to manipulate the
record of a table in a singleton method, in other
words one row at a time.
47
• In other words, 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.

48
Types of Cursors

There are the following two types of Cursors:


• Implicit Cursor
• Explicit Cursor

49
Implicit Cursor

• These types of cursors are generated


and used by the system during the
manipulation of a DML query (INSERT,
UPDATE and DELETE). An implicit
cursor is also generated by the system
when a single row is selected by a
SELECT command.

50
Explicit Cursor

• This type of cursor is generated by the user using


a SELECT command.
• An explicit cursor contains more than one row, but
only one row can be processed at a time. An
explicit cursor moves one by one over the
records.
• An explicit cursor uses a pointer that holds the
record of a row.
• After fetching a row, the cursor pointer moves to
the next row.
51
Main components of Cursors

• Each cursor contains the followings parts,


• Declare Cursor: In this part we declare
variables and return a set of values.
• Open: This is the entering part of the cursor.
• Fetch: Used to retrieve the data row by row
from a cursor.
• Close: This is an exit part of the cursor and
used to close a cursor.

52
Implicit Cursor

53
Using an Implicit Cursor

• Executing a SELECT query creates an implicit cursor


• To retrieve it into a variable use INTO:
– SELECT field1, field2, ...
INTO variable1, variable2, ...
FROM table1, table2, ...
WHERE join_ conditions
AND search_condition_to_retrieve_1_record;
• Can only be used with queries that return exactly one
record

54
Loop in Implicit Cursor

BEGIN FOR row IN (SELECT * FROM employees


WHERE manager_id = 101)
LOOP
DBMS_OUTPUT.PUT_LINE('Name = ' || row.last_name);
END LOOP;
END;
/

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.

• If it returns more than one record, obviously, there will


something wrong.

56
Explicit Cursor

• Use for queries that return multiple records or


no records

• Must be explicitly declared and used

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

• Automatically opens the cursor, fetches the records,


then closes the cursor
• FOR variable_name(s) IN cursor_name LOOP
processing commands
END LOOP;
• Cursor variables cannot be used outside 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

You might also like