Lec6 240302
Lec6 240302
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
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.
• While SQL can perform complex queries and transactions, it lacks the
procedural features required for certain tasks. This is where PL/SQL comes
缺乏某些任務所需的程式功能
• - 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
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
6-11
BINARY_INTEGER
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
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:
• 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;
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;
32
Double bar (||) operator
PL/SQL
33
Manipulating Character
Strings with PL/SQL
• To change case, use UPPER, LOWER, INITCAP
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;
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
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
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
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
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
…