Les 10
Les 10
Modules in PL/SQL
Cursor
❖ Cursor?
• Cursors are memory areas where Oracle executes
SQL statements, stores processing information
Select …
From…
Where…
SERVER RAM
Active Data Set
Contents of a Cursor
10-2
Cursor
❖ When?
• We create a Cursor (is a variable) when we want to
go over a result of a query.
❖ Cursors have two important features:
• Cursors allow you to fetch and process rows
returned by a SELECT statement one row at a time.
• A cursor is named so that it can be referenced.
Type of Description
Cursors
Implicit Oracle automatically declares an implicit cursor every time a SQL statement is
executed.
The user is unaware of this and cannot control or process the information in an implicit
cursor.
Explicit The program defines an explicit cursor for any query that returns more than one row of
data. This means that the programmer has declared the cursor within the PL/SQL code
block. This declaration allows the application to sequentially process each row of data
as the cursor returns it.
10-3
Cursor
❖ Explicit Cursor
NO
YES?
DECLARE OPEN FETCH EMPTY ? CLOSE
•Release
• Create a •Identify •Load the
the
named SQL the active current
active
area set row into
set
variables
10-4
Example
RAD_VALS DECLARE
Pi constant NUMBER(8,7) := 3.1415926;
radius area NUMBER(14,2);
cursor rad_cursor is select * from RAD_VALS;
Rad_cursor
3 rad_value rad_cursor%ROWTYPE;
f BEGIN
e 6 open rad_cursor;
fetch rad_cursor into rad_val;
t
8
area:=pi*power(rad_val.radius,2);
c insert into AREAS values (rad_val.radius, area);
close rad_cursor;
h END;
Rad_val /
AREAS
Radius Area
3 28.27
10-5
The AREAS Table
10-6
Explicit Cursor Attributes
10-7
number_table
Cursor
❖ Ex1: Select id, num (number_table) and insert
into the temp_list table
temp_list
RESULT
10-8
Cursor
number_table
❖ Ex2: Select information from number_table
and print out
10-9
Explicit Cursor
10-10
Modules in PL/SQL
❖ There are 4 types of modules in PL/SQL
• Procedures – series of statements may or may not
return a value
• Functions – series of statements must return a
single value
• Triggers – series of PL/SQL statements (actions)
executing after an event has triggered a condition
(ECA)
• Packages – collection of procedures and function
that has 2 parts:
– a listing and a body.
10-11
Functions and Procedures
10-12
Creating Procedures
CREATE [OR REPLACE] PROCEDURE
procedure_name
[(parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
IS|AS
PL/SQL Block;
❖ Modes:
• IN: procedure must be called with a value for the parameter.
Value cannot be changed
• OUT: procedure must be called with a variable for the parameter.
Changes to the parameter are seen by the user (i.e., call by
reference)
• IN OUT: value can be sent, and changes to the parameter are
seen by the user
❖ Default Mode is: IN
10-13
Procedures
❖ How to execute a Stored Procedure?
• There are two ways to execute a procedure.
– 1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;
– 2) Within another procedure – simply use the procedure name.
procedure_name;
10-14
Procedures
❖ Three Types of Parameters
MODE DESCRIPTION USAGE
IN Passes a value into the program Read-only
Constants, literals, expressions value
Cannot be changed within the program’s default
mode
10-15
Procedures
❖ Ex1
10-16
Procedures
❖ Call a Procedure :
❖ Method 1
❖ Method 2
10-17
Ex2
Procedures
Table: my_log create or replace procedure
num_logged
logon_ (person IN my_log.who%TYPE,
who
num num OUT my_log.logon_num%TYPE)
IS
BEGIN
Peter 3
select logon_num
into num
from my_log
John 4 where who = person;
END;
Joe 2
10-18
Procedures
set serveroutput on
declare
howmany my_log.logon_num%TYPE;
begin
num_logged('John',howmany);
dbms_output.put_line('John log
on..'||howmany||' times');
end;
10-19
❖ Ex3: Create a procedure to add a row to the table my_log
10-20
❖ Ex3’’: Create a procedure to add a row to the table my_log
10-21
FUNCTION
❖ Create a Function
10-22
Creating a Function
10-23
Example
10-24
Function
Call a rating_Message
set serveroutput on
declare
paulRate number:= 3;
begin
dbms_output.put_line(rating_Message(paulRate));
end;
10-25
Trigger
❖ A trigger
• Triggers are stored procedures that execute
automatically when something (event) happens in the
database:
– data modification (INSERT, UPDATE or DELETE)
– schema modification
– system event (user logon/logoff)
❖ Types of PL/SQL Triggers
• 1) Row level trigger - An event is triggered for each
row: upated, inserted or deleted.
• 2) Statement level trigger - An event is triggered for
each sql statement executed.
10-26
Trigger
10-27
Trigger
❖ Syntax of Triggers
10-28
Trigger
10-29
Trigger
10-30
A Sample Trigger
create or replace trigger raise_sal
before update of salary on employees
for each row
when (new.salary > old.salary * 1.2)
begin
dbms_output.put_line(‘Old salary is ‘ ||
:old.salary || ‘, ‘ || ‘New salary is ‘ ||
:new.salary);
dbms_output.put_line(‘The raise is too high!’);
end;
10-31
Row Trigger
❖ Row Trigger
• Fire once for each row that is affected by the event and
satisfies the additional condition in the when clause.
• Must specify for each row.
❖ Predefined references: new & old
• new is applicable for insert and update
• old is applicable for update and delete
• use :new.salary & :old.salary in trigger body
10-32
Trigger Applications
❖ Add a log entry each time the price of a product is
changed.
• The log table:
products_log (pid, username, update_date,
old_price, new_price);
10-33
Trigger Application (cont.)
• Create a trigger:
create or replace trigger update_p_price
after update of price on products
for each row
begin
insert into products_log values
(:old.pid, user, sysdate, :old.price,
:new.price);
end;
10-34
Another Trigger Application
❖ If a student is removed, delete all enrollments by the
student.
create or replace trigger stud_enroll
after delete on students
for each row
begin
delete from enrollments where sid = :old.sid;
end;
10-35
Trigger
10-36
Trigger
10-37
Trigger
❖ 2) Create the price_history_trigger and execute it.
10-38
Trigger
10-39
TRIGGER(tt)
❖ Ví dụ 1: Tạo trigger hiển thị ra thông báo mỗi khi có sự
thay đổi trên bảng my_log hay thông báo khi nhập và xóa dữ
liệu của bảng này
10-40
TRIGGER (tt)
10-41
TRIGGER (tt)
10-42
TRIGGER (tt)
❖ Kiểm tra sự thực thi của trigger T_test_my_log.
Dữ liệu hiện tại của bảng my_log
TEST
10-43
❖ Result “TEST”
❖ Table my_log...
INSERTED
UPDATED
10-45
❖ Lưu ý: để lấy được dữ liệu cũ và mới: PHẢI tạo trigger
Ở mức dòng (FOR EACH ROW)
Bước 2: Tạo trigger
Dữ liệu cũ và
mới sẽ được ghi
vào bảng
my_log_history
Sử dụng
OLD, NEW
để lấy giá trị
cũ và mới
10-46
TRIGGER (tt)
10-47
TRIGGER (tt)
❖ Bước 4: Kiểm tra lại bảng my_log
❖ Số lần truy nhập của Trang đã được
thay đổi
❖ Kiểm tra xem bảng my_log_history đã
có dữ liệu chưa
10-48
TRIGGER (tt)
10-49
TRIGGER (tt)
Chú ý: trước khi tạo trigger trên view, phải vào user SYS để
cấp quyền tạo view cho user LINHNT
10-50
TRIGGER (tt)
10-51
TRIGGER (tt)
❖ Trigger trên View
❖ Ví dụ 3 (tt): kiểm tra dữ liệu hiện tại của
my_log_view
10-52
TRIGGER (tt)
❖ Ví dụ 3(tt): kết quả khi chạy khối lệnh nhập dữ liệu trên
10-53
TRIGGER (tt)
❖ Trigger trên View
❖ Ví dụ 4: tạo trigger hiển thị giá trị trước và sau khi
được thay đổi trên my_log_view
10-54
TRIGGER (tt)
❖ Trigger trên View
❖ Ví dụ 4: kiểm tra sự thực thi của trigger
❖ Thay đổi dữ liệu của my_log_view
10-55
TRIGGER (tt)
❖ Trigger Exception
• Dùng để ngăn chặn các hành động không hợp lệ tác động
vào database
• Oracle engine cung cấp thủ tục
RAISE_APPLICATION_ERROR cho phép lập trình viên
đưa ra thông báo lỗi của mình
• Cú pháp:
• RAISE_APPLICATION_ERROR (ErrorNumber, Message)
– Trong đó: ErrorNumber = -20000 → -20999
– Message: tối đa 2048 byte
10-56
TRIGGER (tt)
Hãy tạo trigger hiển thị thông báo “can not change date of birth”
khi ai đó cố tình muốn thay đổi ngày sinh của người nào đó
trong bảng dữ liệu trên.
10-57
TRIGGER (tt)
❖ Trigger Exception (tt)
• Tạo trigger cảnh báo không cho phép thay đổi dữ liệu trên
trường birth_day của bảng person
10-58
TRIGGER (tt)
10-59
TRIGGER (tt)
10-60
TRIGGER (tt)
10-61
TRIGGER (tt)
10-62
TRIGGER (tt)
10-63
TRIGGER (tt)
10-64
TRIGGER (tt)
❖ Thực hiện lệnh update trên bảng my_log
10-65
TRIGGER(tt)
❖ Ví dụ 2: Tạo trigger để mỗi khi có sự thay đổi trên
trường logon_num ở bảng my_log thì dữ liệu sau khi thay
đổi sẽ được tự động ghi vào bảng khác là log_my_log
❖ Bước 1: Trước khi tạo trigger, phải tạo bảng
log_my_log
10-66
TRIGGER(tt)
10-67
TRIGGER(tt)
❖ Bước 3:
10-68
PACKAGES
10-69
What are they?
10-70
Package structure
❖ Has 2 parts:
• Package Specification
– Declares public procedures etc
– Other programs can access them outside the package
• Package Body
– Implements the public procedures etc but also may specify
private procedures, functions etc
– The private units are only accessible within the scope of the
package itself
– All units declared in specification MUST be implemented in
the body
10-71
Package Specification example
10-72
Package Body
10-73
How do we use them?
empName:=package_name.getName(empID);
10-74