0% found this document useful (0 votes)
23 views74 pages

Les 10

The document provides an overview of modules in PL/SQL, focusing on cursors, procedures, functions, and triggers. It explains the types of cursors (implicit and explicit), how to create and execute procedures and functions, and the purpose and structure of triggers. Additionally, it includes examples and syntax for implementing these PL/SQL components in database operations.

Uploaded by

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

Les 10

The document provides an overview of modules in PL/SQL, focusing on cursors, procedures, functions, and triggers. It explains the types of cursors (implicit and explicit), how to create and execute procedures and functions, and the purpose and structure of triggers. Additionally, it includes examples and syntax for implementing these PL/SQL components in database operations.

Uploaded by

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

LESSON 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

Cursor Current Row

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

Obtain status information about a cursor.

Attribute Type Description


%ISOPEN Boolean Evaluates to TRUE if the cursor
is open.
%NOTFOUND Boolean Evaluates to TRUE if the most
recent fetch does not return a row.
%FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of
rows returned so far.

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

Note: statement FOR


Open, Fetch, Close Cursor
are implementation implicitly
Result

10-9
Explicit Cursor

❖ Ex3: Create a table_num


❖ Print these records with a maso from 3 to 7

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

❖ Up until now, our code was in an anonymous block


❖ It was run immediately
❖ It is useful to put code in a function or procedure
so it can be called several times
❖ Once we create a procedure or function in a
Database, it will remain until deleted (like a table).

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

OUT Passes a value back from the program Write-only


Cannot assign default values value
Must be a variable
A value is assigned only if the program is
successful
IN OUT Passes values in and also sends values back Has to be a
variable

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

CREATE [OR REPLACE] FUNCTION


function_name
[(parameter1 [IN] datatype1,
parameter2 [IN] datatype2,
. . .)]
RETURN datatype
IS|AS
[declaration_section]
BEGIN
...
RETURN (return_value);
END ;

10-22
Creating a Function

❖ Almost exactly like creating a procedure, but you


supply a return type

CREATE [OR REPLACE] FUNCTION


function_name
[(parameter1 [IN] datatype1,
parameter2 [IN] datatype2,
. . .)]
RETURN datatype
IS|AS
PL/SQL Block;

10-23
Example

create or replace function


rating_message(rating IN NUMBER)
return VARCHAR2
AS NOTE THAT YOU DON'T
BEGIN SPECIFY THE SIZE
IF rating > 7 THEN
RETURN 'You are great';
ELSIF rating >= 5 THEN
RETURN 'Not bad';
ELSE
RETURN 'Pretty bad';
END IF;
END;

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

❖ PL/SQL Trigger Execution Hierarchy:


• The following hierarchy is followed when a trigger is fired:
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row
affected.
3) Then AFTER row level trigger fires once for each affected
row. This events will alternates between BEFORE and
AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.

10-27
Trigger

❖ Syntax of Triggers

10-28
Trigger

❖ Statement level trigger

10-29
Trigger

❖ Row level 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

❖ For Example: The price of a product changes


constantly. It is important to maintain the history of the
prices of the products.
❖ We can create a trigger to update the
'product_price_history' table when the price of the
product is updated in the 'product' table.

10-36
Trigger

❖ 1) Create the 'product' table and 'product_price_history' table

10-37
Trigger
❖ 2) Create the price_history_trigger and execute it.

10-38
Trigger

❖ 3) Lets update the price of a product.


UPDATE PRODUCT
SET unit_price = 800
WHERE product_id = 100
• Once the above update query is executed, the trigger fires and
updates the 'product_price_history' table.
❖ 4) If you ROLLBACK the transaction before committing to the
database, the data inserted to the table is also rolled back.

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)

❖ UPDATING, DELETING, INSERTING

Function Name Return Datatype Description


DELETING BOOLEAN The DELETING function returns a
Boolean true when the DML event
is deleting.
INSERTING BOOLEAN The INSERTING function returns
a Boolean true when the DML is
inserting
UPDATING BOOLEAN The UPDATING function returns
a Boolean true when the DML is
updating

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

Joe was deleted


10-44
TRIGGER(tt)
❖ Ví dụ 2: Tạo trigger để trước khi có sự thay đổi dữ liệu
trên bảng my_log thì dữ liệu trước và sau khi thay đổi được
ghi vào bảng khác là my_log_history
❖ Bước 1: Trước khi tạo trigger, Tạo bảng my_log_history

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)

❖ Bước 3: kiểm tra sự thực thi của trigger


❖ Dữ liệu của bảng my_log trước khi thay đổi
❖ Cập nhật lại số lần truy nhập của Trang

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)

❖ Tạo Trigger trên View

10-49
TRIGGER (tt)

❖ Trigger trên View


❖ Ví dụ 3: Tạo View sau:

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)

❖ Trigger trên View


❖ Ví dụ 3 (tt): tạo trigger hiển thị thông báo khi nhập
dữ liệu cho my_log_view

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

❖ Nhập một bản ghi mới vào 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

❖ Kiểm tra lại xem my_log_view đã có thêm dữ liệu mới chưa?

KHÔNG có bản ghi mới???

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)

❖ Ví dụ 5: Bảng person có cấu trúc và dữ liệu như sau:

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)

❖ Trigger Exception (tt)


• Kiểm tra sự thực thi của trigger, khi thay đổi dữ liệu
của bảng person

10-59
TRIGGER (tt)

❖ Ví dụ 6: Kiểm tra thứ tự thực hiện của trigger khi


chương trình có nhiều trigger. Tạo 4 trigger được thực thi
khi có sự kiện UPDATE xảy ra đối với bảng my_log, nhật
ký hoạt động sẽ được ghi vào bảng my_log_check
❖ Trước tiên, tạo bảng my_log_check

10-60
TRIGGER (tt)

❖ 1) BEFORE UPDATE, Statement Level:

10-61
TRIGGER (tt)

❖ 2) BEFORE UPDATE, Row Level:

10-62
TRIGGER (tt)

❖ 3) AFTER UPDATE, Statement Level

10-63
TRIGGER (tt)

❖ 4) AFTER UPDATE, Row Level:

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)

❖ Bước 2: Tạo trigger có tên my_log_update

10-67
TRIGGER(tt)

❖ Bước 3:

10-68
PACKAGES

10-69
What are they?

❖ A collection of PL/SQL objects that are logically


grouped together to form one unit
❖ They can contain:
• Procedures, functions
• Cursors, variables, Constants
• Tables
• Exceptions
❖ Typically, they may contain all routines to process
purchase orders, for example.

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

CREATE OR REPLACE PACKAGE package_name


IS
PROCEDURE sal_raise
(p1 NUMBER, p2 NUMBER); Note there is no
PL/SQL
--------------------------------------------- executable code
FUNCTION div_bal
(div_no IN NUMBER)
RETURN NUMBER;
---------------------------------------------
END package_name; -- not necessary to name package here
-- just for clarity

10-72
Package Body

CREATE OR REPLACE PACKAGE BODY package_name


IS
PROCEDURE sal_raise (p1 NUMBER, p2 NUMBER)
IS
BEGIN
update staff set salary=salary*1.1 where div=p2;
END sal_raise;
---------------------------------------------
FUNCTION div_bal (div_no IN NUMBER)
RETURN NUMBER
IS
bal number;
BEGIN
select sum(salary) into bal from staff where div=div_no;
RETURN bal;
END div_bal;
END package_name;

10-73
How do we use them?

❖ DROP PACKAGE package_name


• Will remove specification and body
❖ DROP PACKAGE BODY package_name
• Will only remove the body
❖ To run/access an element of a package body
Execute package_name.element

empName:=package_name.getName(empID);

The package The function element The parameter


Chú ý: khi một phần tử trong package được gọi thì toàn bộ nội dung của
package sẽ được nạp vào trong hệ thống.

10-74

You might also like