0% found this document useful (0 votes)
8 views62 pages

Lec6 240302

Lecture 6 covers PL/SQL, focusing on variables, data types, DML statements, and flow control. It explains the advantages of PL/SQL over standard SQL, including procedural logic, modularity, and efficient data handling. The lecture also details how to write and execute PL/SQL programs, manipulate data, and utilize various data types and functions.

Uploaded by

david--chin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views62 pages

Lec6 240302

Lecture 6 covers PL/SQL, focusing on variables, data types, DML statements, and flow control. It explains the advantages of PL/SQL over standard SQL, including procedural logic, modularity, and efficient data handling. The lecture also details how to write and execute PL/SQL programs, manipulate data, and utilize various data types and functions.

Uploaded by

david--chin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Lecture 6

PL/SQL ‒
Variable,
Data Type,
DML and
Flow Control
Chapter 8 - Coronel, C., Morris, S. & Rob, P. (2023). Database Systems: Design, Implementation & Management, 14th Edition,
Cengage Learning
Learning Objectives

• LO#1 Learn PL/SQL variables and data types.


• LO#2 Write SELECT and DML statements in PL/SQL.
• LO#3 Understand PL/SQL data type conversion functions.
• LO#4 Understand PL/SQL flow control.
• LO#5 Write and execute PL/SQL programs in SQL*Plus.

6-2
About PL/SQL
• SQL is a powerful language for querying and manipulating data in a
database. However, it's primarily designed for managing and interacting
with structured data in relational databases.

• SQL's capabilities are fundamentally centered around data definition


(DDL), data manipulation (DML), and data control (DCL).

• While SQL can perform complex queries and transactions, it lacks the
procedural features required for certain tasks. This is where PL/SQL comes
缺乏某些任務所需的程式功能

into play, offering several advantages:


程式

• PL/SQL extends SQL by adding the ability to execute procedural logic on


the database server. This includes operations like loops, conditional
分枝
execution, and branching, which are not possible with standard SQL.
3
About PL/SQL
• Modularity: PL/SQL allows you to create modular code with
procedures, functions, packages, and triggers. This modularity
makes it easier to create reusable code and maintain it.

• In summary, while SQL is sufficient for basic querying and data


manipulation, PL/SQL is necessary when you need more control
over the logic, want to optimize performance for complex
operations, or need to take advantage of server-side processing and
modular programming techniques.

• It essentially allows you to do more with your Oracle database,


leveraging the full power of procedural programming along with the
strengths of SQL.
4
About PL/SQL
• 1.Data Manipulation and Query Statements of SQL: This
refers to the standard operations you can perform with
SQL, such as `SELECT` (to query data), `INSERT` (to add
data), `UPDATE` (to modify data), and `DELETE` (to remove
data).

• 2. Procedural Units of Code: These are constructs


provided by procedural programming languages that
allow for variables, control structures like loops and
conditionals, and the definition of modular code (such as
procedures, functions, packages, and triggers).
5
About PL/SQL
• When we combine both:

• - SQL statements can be directly included in the blocks of PL/SQL code. This means
that within a PL/SQL function or procedure, you can have `SELECT`, `INSERT`,
`UPDATE`, and `DELETE` statements, among other SQL operations.

• - These SQL statements are executed as part of the procedural workflow. For example,
you might retrieve some data with a `SELECT` statement into a PL/SQL variable, use a
`FOR LOOP` to iterate over the result set, make decisions with `IF` statements based
on the data, and possibly update the data with an `UPDATE` statement.

• - The procedural logic allows for more complex operations than would be possible
with standalone SQL. It can control the flow of execution, allowing for more
sophisticated data operations that depend on conditional logic and iterative
processing.

• - The SQL operations within PL/SQL blocks are processed by the database server,
allowing for efficient execution and data handling.
6
About PL/SQL
– PL/SQL is an extension to SQL with design features of
programming languages.
– An interpreted language
– Data manipulation and query statements of SQL are
included within procedural units of code.

6-7
PL/SQL Environment
PL/SQL engine
PL/SQL Procedural
PL/SQL PL/SQL
block block SQL Statement
Executor

SQL Statement Executor

Oracle Server

6-8
Block Structure for Anonymous
PL/SQL Blocks

6-9
Variables and Data Types
• 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;

today_date DATE;

6-10
NUMBER data type stores numbers with the magnitude range e-130 to 10e125
BINARY_INTEGER data type stores signed integers with the magnitude range -231 to 231

Scalar Data Types


INTEGER, INT, and SMALLINT data types store integers with a maximum precision of 38 decimal digits

• Represent a single value

DEC, DECIMAL, and NUMERIC data types


store fixed-point numbers with a
maximum precision of 38 decimal digits

DOUBLE PRECISION and FLOAT data


types store floating-point numbers with
a maximum precision of 126 binary
digits, which is roughly equivalent to 38
decimal digits

REAL data type stores floating-point


numbers with a maximum precision of
63 binary digits, which is roughly
equivalent to 18 decimal digits

A fixed point number just means that


there are a fixed number of digits after
the decimal point.

6-11
BINARY_INTEGER

INTEGER, INT, and SMALLINT

12
Real

Double precision

13
BOOLEAN

14
Composite and Reference Variables
Turn on the output (that is, DBMS_OUTPUT PUT_LINE) of
• Composite variables stored procedures or PL/SQL blocks in SQL*Plus
– RECORD: contains multiple scalar values, similar to a table record
– TABLE: tabular structure with multiple columns and rows
– VARRAY: variable-sized array varray.sql
SQL> set termout on Turn off script file output
SQL> set serveroutput on
SQL> declare
2 TYPE phone_no_tab IS VARRAY(3) OF VARCHAR2(20);
3 phone_nos phone_no_tab := phone_no_tab('3746-0111',
4 '3746-0108',
5 '3746-0105');
6 begin
7 dbms_output.put_line('phone_no(1) is ' || phone_nos(1));
8 end;
9 /
phone_no(1) is 3746-0111

PL/SQL procedure successfully completed.


set termout on

16
• 1. `set termout on`: This command is used in SQL*Plus or SQLcl to specify that the
output from subsequent commands should be displayed on the terminal. Since it's
already on by default, this command doesn't change anything unless `TERMOUT` was
previously set to off.

• 2. `set serveroutput on`: This enables the display of output generated by the
`DBMS_OUTPUT` package in the session. By default, server output is not shown until
this is enabled. It's necessary to run this command if you want to see output from
`DBMS_OUTPUT.PUT_LINE` and similar procedures.

• 3. The `declare` section starts an anonymous PL/SQL block. Inside this block, the
following is declared:

• - `TYPE phone_no_tab IS VARRAY(3) OF VARCHAR2(20);`: This line declares a PL/SQL


type `phone_no_tab` which is a variable-size array (VARRAY) that can contain up to 3
elements, each of which is a `VARCHAR2` string with a maximum length of 20
characters.

• - `phone_nos phone_no_tab := phone_no_tab('3746-0111', '3746-0108', '3746-


0105');`: This line initializes a variable `phone_nos` of the previously defined type
`phone_no_tab` with three phone numbers.
17
• 4. The `begin ... end;` section is the body of the anonymous PL/SQL block where the actual
processing occurs:

• - `dbms_output.put_line('phone_no(1) is ' || phone_nos(1));`: This line outputs the first element


of the `phone_nos` array concatenated with the string `'phone_no(1) is '`. The
`DBMS_OUTPUT.PUT_LINE` procedure is used for this purpose, and because `SET SERVEROUTPUT
ON` was executed before, this output will be displayed in the SQL*Plus or SQLcl session.

• 5. After executing the PL/SQL block, SQL*Plus or SQLcl displays the result of the
`DBMS_OUTPUT.PUT_LINE` call:

• ```
• phone_no(1) is 3746-0111
• ```

• 6. Finally, you see the message `PL/SQL procedure successfully completed.`, indicating that the
PL/SQL block was executed without errors.

• So in summary, when you run this code in an SQL*Plus or SQLcl session with server output
enabled, you will see the first phone number from the `phone_nos` array printed out, followed by
a message indicating that the PL/SQL block executed successfully.

18
Composite and Reference Variables
• Reference variables
– Directly reference a specific database field or record and assume the
data type of the associated field or record
cretabs.sql
– %TYPE: same data type as a database field
– %ROWTYPE: same data type as a database record reftype.sql

SQL> DECLARE
2 r_emp emp%ROWTYPE;
3 n_empno emp.empno%TYPE := 7902;
4 BEGIN
5 SELECT *
6 INTO r_emp
7 FROM emp
8 WHERE empno = n_empno;
9 -- print out the employee's name
10 DBMS_OUTPUT.PUT_LINE(r_emp.ename);
11 END;
12 /
FORD
Retrieving Data in PL/SQL
• Retrieve the order date and the ship date for
the specified order. Reference variables
• Example
DECLARE
DECLARE
v_orderdate
v_orderdate ord.orderdate%TYPE;
ord.orderdate%TYPE;
v_shipdate
v_shipdate ord.shipdate%TYPE;
ord.shipdate%TYPE;
BEGIN
BEGIN
SELECT
SELECT orderdate,
orderdate, shipdate
shipdate
INTO
INTO v_orderdate,
v_orderdate, v_shipdate
v_shipdate
FROM
FROM ord
ord
WHERE
WHERE ordid
ordid == 620;
620;
...
...
END;
END;

shipdate.sql
6-20
Composite and Reference Variables

21
Composite and Reference Variables

22
Composite and Reference Variables

23
Comments
• Comments:
– Not executed by interpreter
– Enclosed between /* and */
– On one line beginning with --

6-24
Arithmetic ( 算術 ) Operators

6-25
Assignment Statements
• Assigns a value to a variable
• variable_name := value;

• Value can be a literal:


current_s_first_name := 'John';
• Value can be another variable:
current_s_first_name := s_first_name;

6-26
27
Executing a PL/SQL
Program in SQL*Plus

todaydate.sql
• Create program in text editor
• Paste into SQL*Plus window
• Press Enter, type / then enter to execute

6-28
29
PL/SQL Data Conversion Functions

6-30
Manipulating Character
Strings with PL/SQL
• To concatenate two strings in PL/SQL, you use the double
bar (||) operator:
– new_string := string1 || string2;

• To remove blank leading spaces use the LTRIM function:


– string := LTRIM(string_variable_name);

• To remove blank trailing spaces use the RTRIM function:


– string := RTRIM(string_variable_name);

• To find the number of characters in a character string use


the LENGTH function:
– string_length := LENGTH(string_variable_name);
stringm.sql 6-31
Double bar (||) operator

32
Double bar (||) operator

PL/SQL

33
Manipulating Character
Strings with PL/SQL
• To change case, use UPPER, LOWER, INITCAP

• INSTR function searches a string for a specific substring:


– start_position := INSTR(original_string, substring);

• SUBSTR function extracts a specific number of characters from


a character string, starting at a given point:
– extracted_string := SUBSTR(string_variable, starting_point,
number_of_characters);

6-34
SUBSTR(string_varia
ble, starting_point,
number_of_characte
6
3 rs);
4
starting from O, then
count 3 char, OHN
35
SELECT Statements in PL/SQL
• The INTO clause is required.
• Example
DECLARE
DECLARE
v_deptno
v_deptno NUMBER(2);
NUMBER(2);
v_loc
v_loc VARCHAR2(15);
VARCHAR2(15);
BEGIN
BEGIN
SELECT
SELECT deptno,
deptno, loc
loc
INTO
INTO v_deptno,
v_deptno, v_loc
v_loc
FROM
FROM dept
dept
WHERE
WHERE dname
dname == 'SALES';
'SALES';
...
...
END;
END;

Queries Must Return One and Only One Row

select.sql
6-36
Retrieving Data in PL/SQL
• Return the sum of the salaries for all
employees in the specified department.
• Example
DECLARE
v_sum_sal emp.sal%TYPE;
v_deptno NUMBER NOT NULL := 10;
BEGIN
SELECT SUM(sal) -- group function
INTO v_sum_sal
FROM emp
WHERE deptno = v_deptno;
END;

salsum.sql
6-37
38
Inserting Data
• Add new employee information to the EMP
table.
• Example
BEGIN
BEGIN
INSERT
INSERT INTO
INTO emp(empno,
emp(empno, ename,
ename, job,
job, deptno)
deptno)
VALUES (7888,'HARDING','CLERK', 10);
VALUES (7888,'HARDING','CLERK', 10);
END;
END;

insert.sql

6-39
Updating Data
• Increase the salary of all employees in the
EMP table who are Analysts.
• Example
DECLARE
v_sal_increase emp.sal%TYPE := 2000;
BEGIN
UPDATE emp
SET sal = sal + v_sal_increase
WHERE job = 'ANALYST';
END;

updatesal.sql
6-40
Deleting Data
• Delete rows that belong to department 30
from the EMP table.
• Example
DECLARE
DECLARE
v_deptno
v_deptno emp.deptno%TYPE
emp.deptno%TYPE :=
:= 30;
30;
BEGIN
BEGIN
DELETE
DELETE FROM
FROM emp
emp
WHERE
WHERE deptno
deptno == v_deptno;
v_deptno;
END;
END;

delete.sql
6-41
COMMIT and ROLLBACK Statements
– Initiate a transaction with the first DML
command to follow a COMMIT or
ROLLBACK.
– Use COMMIT and ROLLBACK SQL
statements to terminate a transaction
explicitly.

6-42
IF/THEN
• Flow control structures
– Alter order in which statements execute
– Based on values of certain variables
• Condition
– Expression evaluates to TRUE or FALSE
– If TRUE commands execute

6-43
if.sql

• Question: What two lines do you need to change to make the


program display Today is not Friday?

6-44
IF/THEN/ELSE ifb.sql

6-45
Nested IF/THEN/ELSE
ifc.sql

6-46
IF/ELSIF ifd.sql

6-47
Logical Operators AND, OR, and NOT
• Create complex expressions for decision control structure
condition
• AND: Expressions on both sides of operator must be true
for combined expression to be TRUE
• OR: Expressions on either side of operator must be true
for combined expression to be TRUE
• Order of evaluation (precedence):
– NOT
– AND
– OR

• Parentheses can be used to override precedence and force the


program to evaluate the OR first 6-48
Loops
• Systematically executes program
statements
• Periodically evaluates exit condition to
determine if loop should repeat or exit
• PL/SQL has 5 types of loop structure:
– LOOP…EXIT
– LOOP…EXIT WHEN
– WHILE…LOOP
– Numeric FOR loop
– Cursor FOR loops

6-49
The LOOP...EXIT Loop
SQL statement
Syntax
LOOP
CREATE TABLE count_table [program statements]
(counter NUMBER(2)); IF condition THEN
EXIT;
END IF;
[additional program
statements]
END LOOP;

loopexit.sql

6-50
The LOOP...EXIT WHEN Loop
Syntax (posttest loop)
LOOP
program statements
EXIT WHEN condition;
END LOOP;

loopexitwhen.sql

6-51
The WHILE...LOOP
Syntax
• WHILE…LOOP is WHILE condition LOOP
program statements
a Pretest loop END LOOP;

whileloop.sql

Q: Why the SELECT *


FROM count_table
shows only counter
6 to 10?
The Numeric FOR Loop
• Does not require explicit counter increment
Syntax
FOR counter_variable IN start_value ..
end_value
LOOP
program statements
END LOOP;

forloop.sql
Cursor
• A pointer to memory location on database
server
• Used to:
– Retrieve and manipulate database data in
PL/SQL programs
• Types:
隱含的
– Implicit cursor
明顯的
– Explicit cursor

6-54
55
Implicit Cursors
• Context area
– A memory location created by INSERT, UPDATE, DELETE, or
SELECT
– Contains information about query (# rows, etc.)
• Active set
– Set of data rows that query retrieves when a SELECT query is
issued
• Implicit cursor
– A pointer to the context area
– Called so, because you do not need to write code to
explicitly create the cursor or retrieve its values
– Used to assign output of SELECT query to PL/SQL program
variables when query will return only one record*
6-56
* Error occurs if query returns no records or more than one record
Implicit Cursors
• To retrieve data using implicit cursor in PL/SQL,
you add an INTO clause to the SELECT query
• Syntax:
SELECT field1, field2, ...
INTO variable1, variable2, ...
FROM table1, table2, ...
WHERE join_conditions
AND search_condition_to_retrieve_1_record;
• Variables must be declared in Declaration
section
• Variables must have same data types as fields
• To avoid errors, %TYPE reference data type
should be used 6-57
Explicit Cursors
• Retrieve and display data in PL/SQL programs
for query that might
– Retrieve multiple records
– Return no records at all
• Must explicitly write the code to
– Declare cursor
– Open
拿來 cursor

– Fetch data rows


– Close cursor

6-58
Explicit Cursors
• Declare explicit cursor syntax:
– CURSOR cursor_name IS select_query;
• Open explicit cursor syntax:
– OPEN cursor_name;
• Fetch values using LOOP…EXIT WHEN loop:
LOOP
FETCH cursor_name INTO
variable_name(s);
EXIT WHEN cursor_name%NOTFOUND;
• Close cursor syntax:
– CLOSE cursor_name;

Note: At this point, system doesn’t check syntax error in the query. It creates the memory
structure to store the active set.
6-59
Using %TYPE
ename_cursor.sql

SQL> DECLARE
2 current_deptno NUMBER(2);
3 CURSOR ename_cursor IS
4 SELECT ename
5 FROM emp At this point, what
6 WHERE deptno = current_deptno;
7 current_ename emp.ename%TYPE;
is the value for
8 BEGIN current_deptno?
9 current_deptno := 20;
10 OPEN ename_cursor;
11 LOOP
12 FETCH ename_cursor INTO current_ename;
13 EXIT WHEN ename_cursor%NOTFOUND;
14 DBMS_OUTPUT.PUT_LINE(current_ename);
15 END LOOP;
16 CLOSE ename_cursor;
17 END;
18 /
JONES

PL/SQL procedure successfully completed. 6-60


61
62

You might also like