Вы находитесь на странице: 1из 548

ORACLE PRESS

OSBORNE

PL/SQL

) PL/SQL

OFFICIAL AUTHORIZED

Oracle Press
ONLY

F R O M O S li R N 1-

ORACLG

Oracle Press

Oracle9/ PL/SQL
Programming

Scott Urman

McGraw-Hill/Osborne
New York Chicago San Francisco
Lisbon London Madrid Mexico City Milan
New Delhi San Juan Seoul Singapore Sydney Toronto

Oracle?/

PL/SQL

""

OracleQ PL/SQL
Programming
Scott Urman
Copyright 2002
All rights reserved
Oracle 9
PL/SQL

.
.
.
.
Copyright 2002 by The McGraw-Hill Companies. All rights reserved.
McGraw-Hill/Osborne
2600 Tenht Street
Berkeley, California 94710
U.S.A.
ISBN 0-07-219147-3
"", 2004
. N : OAI (03)
N : 070612 30.09.97 .
ISBN 5-85582-225-7

15.09.2004 70x100/16
N1 -
.. 34 1500 N f9/

""
123100, , ., . 13/6, . 1 (. )
: (095)256-02-83
: (95)259-01-62
WWW.LORY-PRESS.RU


PL/SQL


Oracle. JSP Oracle Text,
JDBC, PL/SQL OCI. , Oracle,
Oracle. , . "OracleS PL/SQL
Programming" "OracleSi Advanced PL/SQL Programming".

, , . .

.
.
, .
, Osborne,
. , ,
, .

Scott.Urman@oracle.com.
.
.


Oracle .
, , .
Oracle , , Oracle , .
PL/SQL ,' ""
Oracle, "", .. . PL/SQL .
, PL/SQL ("Oracle PL/SQL Programming", 1996 .), PL/SQL 2.3 Oracle? Release 7.3, PL/SQL.
("OracleS PL/SQL Programming", 1997 .) , , OracleS Release
8.0. ("OracleSz Advanced PL/SQL Programming")
2000 . ,
PL/SQL.
, 19. "OracleS i Advanced PL/SQL Programming"
PL/SQL.


? ,
19. , 3
CASE ( 19) PL/SQL. .


PL/SQL. , ,
PL/SQL .
12, "OracleS . PL/SQL" (. "").


12 3 . : " ", " PL/SQL" " PL/SQL".

viii

I.
PL/SQL , . PL/SQL.

1. PL/SQL
PL/SQL . , PL/SQL
, . ,
.

2.
PL/SQL ,
.
PL/SQL, . .

II. PL/SQL
PL/SQL, , , SQL,
SQL, , .

3. PL/SQL
.
, PL/SQL, .

4. SQL PL/SQL

PL/SQL . SQL - .
SQL DML,
.

5. SQL
SQL , .

6.
.
. . , .

ix

7.
, . PL/SQL
( Java),

. , , .

8.
PL/SQL.
,
(varray).
. 6 , ,
.

Hi. PL/SQL
, , , PL/SQL.

9. ,
( ) PL/SQL ,
, .
.

10. ,
10 . SQL-
. .

11.
PL/SQL,
: DML-onepa, INSERT, DDL-, .
DDL. .
12.

PL/SQL: , SQL, LOB
.
: DBMS_ALERT, DBMS_JOB, DBMS_LOB,
DBMS_PIPE, DBMS_SQL UTL_FILE.

OracleQz, UTLJTCP, UTL_HTTP,


UTL_SMTP UTLJNADDR.

PL/SQL.

.

, Oracle PL/SQL.

. PL/SQL
, PL/SQL.

PL/SQL.

.
,
, PL/SQL.

1 PL/SQL


PL/SQL Oracle
Oracle

2



SQL'Plus
Rapid SQL
SQL Navigator . . . .'
TOAD
SQL-Programmer
PL/SQL Developer

II

PL/SQL

3 PL/SQL






LOB

%TYPE

IF-THEN-ELSE
CASE. .

'

7
7
8
9
9
10
10
11
12
13
13
15
16

25
26
31
32
33
39
47
52
56
59
63

65
67
73
76
78
79
81
83
84
85
94
95
95
95
95
97
99
102
102
106
110

xii

GOTO


%ROWTYPE





4 SQL PL/SQL
SQL PL/SQL
SQL
SELECT
INSERT
UPDATE
DELETE
WHERE

RETURNING

CURRVAL NEXTVAL
LEVEL '
ROWID
ROWNUM

GRANT REVOKE
. . . . .
COMMIT ROLLBACK



5 SQL
SUBSTR, SUBSTRB, SUBSTRC, SUBSTR2 SUBSTR4
SOUNDEX
INSTR, INSTRB, INSTRC, INSTR2 INSTR4
LENGTH, LENGTHS, LENGTHC, LENGTH2 LENGTH4
WIDTH.BUCKET
-
CHAR ( -)
TO~CHAR ()
DATE
NUMBER
TIMESTAMPnTO TIMESTAMPJZ
DUMP
ISERENV
6

114
117
120
122
123
125
126
126
127
127

'

......

129
131
.132
134
136
138
138
139
142
144
145
146
147
147
149
149
149
150
152
153
155
156
157
158
163
167
168
170
171
176
179
183
185
187
187
188
193
194
197
199
207

xiii


WHILE
FOR
NO DATA FOUND %NOTFOUND
SELECT FOR UPDATE







209
211
212
213
214
219
220
221
222
222
'224
226

. 227


230

234

236
EXCEPTION INIT
242
RAISE_APPLICATION_ERROR
243
,
246
,
249
, . . . . 251

253

254

255

265










EXISTS
COUNT
LIMIT
FIRST LAST
NEXT PRIOR
EXTEND
TRIM
DELETE

267
271
274
277
278
280
285
290
297
299
300
300
300
301
304
306

III PL/SQL
9 ,

.
CALL. .

.

309
311
313
318
337
340
340

xiy

10 ,








KEEP
UNKEEP .
SIZES
ABORTED_REQUEST_THRESHOLD

11
DML





, . .

342
344
347
350

353
354
.357
362
363
374
380
390
398
402
402
403
403

405
410
420
426
432
437
441
442

12

447


SQL




DBMS SQL
DBMS PIPE
DBMS ALERT
UTL TCP
UTL SMTP
UTL HTTP
UTL INADDR
DBMS JOB
DBMSJ.OB

448
451
456
463
468
470
472
473
474
477
477
478
479
479
480

IV

485

. . 487
DBMS ALERT
DBMS APPLICATION INFO
DBMS AQ
DBMS AQADM
DMBS AQELM
DBMS BACKUP RESTORE .

488
488
489
489
489
. 489

DBMS DDL
DBMS DEBUG
DBMS DEFER
DBMS DEFER QUERY
DBMS DEFER SYS
DBMS DESCRIBE
DBMS DISTRIBUTED TRUST.ADMIN
DBMS FGA
DBMS FLASHBACK
DBMS HS
DBMS HS PASSTHROUGH
DBMS'lOf
DBMS~JAVA
DBMS JOB
DBMS LDAP
DBMS LIBCACHE
DBMS'LOB

DBMS LOCK
DBMSJ.OGMNR
DBMS LOGMNR CDC PUBLISH
DBMS LOGMNR CDC SUBSCRIBE
DBMS LOGMNR_D
DBMS METADATA

xv

489
490
490
490
490
491
491
491
491
492
492
492
492
492
493
493
493

493
494
494
494
494
494

DBMS'MVIEW (DBMS SNAPSHOT)


DBMS'OBFUSCATION'TOOLKIT

494
495

DBMS'OFFLINE OG
DBMS OFFLINE SNAPSHOT
DBMS OLAP
DBMS ORACLE TRACE AGENT
DBMS ORACLE TRACE USER

495
495
495
496
496

DBMS ODCI

495

DBMS'OUTLN "...".

496

DBMS PIPE
DBMS'PROFILER

497
.497

DBMS OUTLN EDIT


DBMS OUTPUT.
DBMS PCLXUTIL

DBMS'RANDOM
DBMS'RECITIFIER DIFF
DBMS REDIFINITION
DBMS REFRESH

496
496
496

497
497
497
498

DBMS REPAIR'
DBMS REPCAT, DBMS REPCAT ADMIN, DBMS REPCAT INSTANTIATE,
DBMS REPCAT RGTuDBMS REPUTIL
DBMS RESOURCE MANAGER
DBMS RESOURCE MANAGER PRIVS

498

DBMS'RLS

499

DBMS RESUMABLE

DBMSlROWID
DBMS_SESSION
DBMS SHARED POOL
DBMS SPACE DBMS SPACE ADMIN
DBMS SQL

498
498
499

499
499
499
500
500

xvi

DBMS STANDARD STANDARD


DBMS'STATS
DBMS TRACE
DBMS TRANSACTION
DBMS TTS

DBMS'TYPES
DBMS UTILITY

500
500
500
501
501

501
501

DBMS WM
DBMS'XMLQUERY, DBMS XMLSAVE XMLGEN
DEBUG EXTPROC. . . . 7
SDO CS, SDO GEOM, SDE LRS, SDO MIGRATE SDO TUNE . . . . . .
UTL COLL
"
"
UUENCODE
'
UTL FILE
UTL HTTP

501
501
502
502
502
502
502
503

UTLRAW
UTL_REF
UTL.SMTP
UTL TCP
UTLJJRL

503
503
503
504
504

UTL'INADDR
UTL'PG

PL/SQL


,
, LOB,
OracleS/ 19/


, .

,
,


sos
sos

505
509
510
511
511
512
514
515
518
519
521
522
524
525
526
527
527

1
PL/SQL

L/SQL ,
Oracle . PL/SQL
, PL/SQL
. Oracle. PL/SQL ,
. PL/SQL, . ,
.

PL/SQL
Oracle . , ,
(SQL, Structured Query Language; ""). SQL ,

. , SQL-
(students),
(major) (nutrition):
[_J DELETE FROM students
WHERE major = 'Nutrition';
(, , s t u d e n t s ,
.)
SQL . , , , , .
DELETE () ,
, . , , , , ,
.
, COBOL, . ,
(3GL, third generation language), . , DELETE :
)

LOOP ( )
IF () major = 'Nutrition' THEN ()
DELETE () ;
END IF ( );
END LOOP ( );

PL/SQL

- , C++
Java, . - , .
. , SQL, ,
( )
. , , . 3GL
. PL/SQL,
SQL ( 4GL)
3GL.
PL/SQL Procedural Language/SQL ( /SQL).
, PL/SQL SQL,
, :
( ,
)
,

(OracleS )
Oracle SQL, .
, . , .
PL/SQL:
) - 3gl_4gl.sql
DECLARE

/* , SQL- */
v_NewMajor VARCHAR2(10) := 'History';
v_FirstName VARCHAR2(10) := 'Scott';
v_LastName VARCHAR2(10) := 'Urman';
BEGIN
/* students */
UPDATE students
SET major = v_NewMajor
WHERE first_name = v_FirstName
AND last_name = v_LastName;
/* , . , . */
IF SQL%NOTFOUND THEN
INSERT INTO students (ID, first_name, last_name, major)
VALUES (student_sequence.NEXTVAL, v_FirstName, v_LastNatne,
v_NewMajor);
END IF;
END;

SQL- (UPDATE () INSERT ()), SGL- ( IF).

,
,
( students
student_sequence).
tables, sql, ""
: www. lory-press, ru.

" ".

PL/SQL , SQL 3GL. , .


, , .

PL/SQL
/ .
/
.

Oracle

SQL

SQL

Oracle

SQL

SQL

PL/SQL

. 1.1. PL/SQL /

PL/SQL

SQL,
, SQL- (.
. 1.1). SQL-
PL/SQL (.
. 1.1). ,
.
, . SQL- ,
.
PL/SQL
. ( HTML-) ,
.
PL/SQL (. 2).

Oracle ANSI (American National Standards Institute ) SQL,


ANSI/ISO/IEC 9075-1:1999 "Database Language SQL". , SQL99 ( SQL2), SQL SGL-,
PL/SQL. Oracle9 ,
CORE .
Oracle SQL Reference.

PL/SQL
PL/SQL . .


PL/SQL (block).
PL/SQL , .
, , . :
Q DECLARE
/* - , ,
PL/SQL. */
BEGIN
/* - SQL-.
. */
EXCEPTION
/* -
. */
END;

. .
PL/SQL
.
PL/SQL Ada. , Ada, PL/SQL.
. Ada , , .



,
. ,
,
. PL/SQL,
, , ,
:
Q -- Error.sql
DECLARE
v_ErrorCode NUMBER;
v_ErrorMsg VARCHAR2(200);
v_Currentllser VARCHAR2(8);
v_Information VARCHAR2(100);
BEGIN

/* */
EXCEPTION
WHEN OTHERS THEN
-
- .
v_ErrorCode := SQLCODE;
v_ErrorMsg := SQLERRM;
v_CurrentUser := USER;
v_Information := ' Error encountered on ' ||
TO_CHAR(SYSDATE) || ' by database user ' || v_CurrentUser;
- log_table.
INSERT INTO log_table (code, message, info)
VALUES (v_ErrorCode, v_ErrorMsg, v_Information);
END;

, ,
,
(. " ").

PL/SQL


PL/SQL
. (variable) , . v _ C u r r e n t l l s e r , v _ E r r o r C o d e v _ I n f o r m a t i o n .
.

(type). , . PL/SQL
, :
Q DECLARE

v_StudentName
VARCHAR2(20);
v_CurrentDate DATE;
v_NumberCredits NUMBER(3);

- :
[_J

DECLARE
v_LoopCounter BINARY_INTEGER;
v_CurrentlyRegistered BOOLEAN;

PL/SQL , : .
, :
)

DECLARE

TYPE t_StudentRecord IS RECORD (


FirstName
VARCHAR2(10),
LastName
VARCHAR2(10),
CurrentCredits NUMBER(3)
);
v_Student t_StudentRecord;


PL/SQL .
. IF. ,


tempjtable:
Q Conditional.sql
DECLARE
v_TotalStudents NUMBER;
BEGIN
-
SELECT COUNT(*)
INTO v_TotalStudents
FROM students;

10

1
- temp_table
IF v_TotalStudents = THEN
INSERT INTO temp.table (char_col)
VALUESC ');
ELSEIF v_TotalStudents < 5 THEN
INSERT INTO tempjtable (char_col)
VALUESC' ');
ELSEIF v_TotalStudents < 10 THEN
INSERT INTO temp_table (char_col)
VALUES(' ');
ELSE
INSERT INTO temp_table (char_col)
VALUES(' ');
END IF;
END;


PL/SQL . (loop) . ,
1 50 temp_table:
Q Simple Loop, sql
DECLARE
v_LoopCounter BINARY_INTEGER := 1;
BEGIN
LOOP
INSERT INTO temp_table (num_col)
VALUES (v_LoopCounter);
v_LoopCounter := v_LoopCounter + 1;
EXIT WHEN v_LoopCounter > 50;
END LOOP;
END;

FOR. . , , :
)

NumericLoop.sql
BEGIN
FOR v_LoopCounter IN 1..50 LOOP
INSERT INTO temp_table (num_col)
VALUES (v_LoopCounter);
END LOOP;
END;

(cursor) ,
SELECT ().

PL/SQL

11

. , ,
:
[_| CursorLoop.sql
DECLARE
v_FirstName VARCHAR2(20);
v_LastName VARCHAR2(20);
- .
SQL-,
- .
CURSOR c_Students IS
SELECT first_name, last_name
FROM students;
BEGIN
- .
OPEN c_Students;
LOOP
- .
FETCH c_Students INTO v_FirstName, v_LastName;
-- , .
EXIT WHEN c_Students%NOTFOUND;
/* */
END LOOP;
-- .
CLOSE c_Students;
END;


( (subprograms)) PL/SQL,
, . ,
PrintStudents,
DBMS_OUTPUT.
(_] PrintStudents.sql
CREATE OR REPLACE PROCEDURE PrintStudents(
pjtejor IN students.major%TYPE) AS
CURSOR c_Students IS
SELECT first_name, last_name
FROM students
WHERE major = p_Major;
BEGIN
FOR v_StudentRec IN c_Students LOOP
DBMS_OUTPUT.PUT_LINE(v_StudentRec.first_name|| ' ' |l
v_StudentRec.last_name);
END LOOP;
END;

12


, , :
Q - PrintStudents.sql
SQL> BEGIN
2
PrintStudents ('Computer Science');
3 END;
4/

Scott Smith
Joanne Junebug
Shay Shariatpanahy

DBMS_OUTPUT. PUTJ.INE
SQL*Plus, set serveroutput on
(. 2).

, . (package) : () .
, . , RoomsPkg ,
rooms:
RoomsPkg.sql
CREATE OR REPLACE PACKAGE RoomsPkg AS

PROCEDURE NewRoom(p_Building rooms. building%TYPE,


p_RoomNum rooms. room_number%TYPE,
p_NumSeats rooms.number_seats%TYPE,
p_Description rooms.description%TYPE);
PROCEDURE.DeleteRoom(p_RoomIDIN rooms.room_id%TYPE);
END RoomsPkg;
CREATE OR REPLACE PACKAGE BODY RoomsPkg AS

PROCEDURE NewRoom(p_Building rooms. building%TYPE,


p_RoomNum rooms. room_number%TYPE,
p_NumSeats rooms. number_seats%TYPE,
p_Description rooms.description%TYPE) IS
BEGIN
INSERT INTO rooms

(room_id, building, room_number, number_seats, description)


VALUES

(room_sequence.NEXTVAL, p_Building, p_RoomNum, p_NumSeats,


p_Description);
END NewRoom;
PROCEDURE DeleteRoom(p_RoomID IN rooms.room_id%TYPE) IS
BEGIN

PL/SQL

13

DELETE FROM rooms


WHERE room_id = p_RoomID;
END DeleteRoom;
END RoomsPkg;


PL/SQL
. PL/SQL
: , (OracleS ) (OracleS ).
:
Q Collections, sql
DECLARE

TYPE t_IndexBy IS TABLE OF NUMBER


INDEX BY BINARY_INTEGER;
TYPE t_Nested IS TABLE OF NUMBER;
TYPE t_Varray IS VARRAY(10) OF NUMBER;
v_IndexBy t_IndexBy;
v_Nested t_Nested;
v_Varray t_Varray;
BEGIN
v_IndexBy(1) := 1;
v_IndexBy(2) := 2;
v_Nested := t_Nested(1, 2, 3, 4, 5);
v_Varray := t_Varray(1, 2);
END;

,
. , PL/SQL, Oracle
.

PL/SQL Oracle
PL/SQL Oracle. PL/SQL, 1.0, Oracle 6. Oracle? PL/SQL 2.x OracleS PL/SQL 8,
OracleSi ( OracleS.1) PL/SQL 8.1, a OracleQi PL/SQL 9.0. PL/SQL ,
1.1.
. PL/SQL 2.0
9.1. , ,
:
, PL/SQL 8.0 ,
, .

14

, PL/SQL 8.1 ,
, SQL.
, PL/SQL 9.1 ,
, .
1.1. Oracle PL/SQL

Oracle


PL/SQL

1.0

7.0

2.0

CHAR .
(, , ).
, : .
DBMS_PIPE
DBMS.ALERT.
SQL*Plus Server Manager
DBMS_OUTPUT.

7.1

2.1

, .
SQL- ,
.
PL/SOL DBMS_SQL

7.2

2.2

7.3

2.3

(
).
/ UTL_FILE.
PL/SQL .
, .

8.0

8.0

.
: .
Advanced Queuing ( ).
.
LOB ( ).

8.1

8.1

SQL.
Java.
.
NOCOPY.
.
.

9.0

9.0

.
CASE..
DATETIME TIMESTAMP.
.

.
, .
PL/SQL
- DBMSJOB.

PL/SQL

15

PL/SQL,
. . ,
:
Connected to:

OracleS Enterprise Edition Release 8.0.6.0.0 - Production


With the Objects option
PL/SQL Release 8.0.6.0.0 - Production

Connected to:
Oracle8i Enterprise Edition Release 8.1.7.1.0 - Production
With the Partitioning and Java options
PL/SQL Release 8.1.7.1.0 - Production

Connected to:
Oracle9i Enterprise Edition Release 9 . 0 . 1 . 0 . 0 - Production
With the Partitioning option
JServer Release 9.0.1.0.0 - Production
, PL/SQL
. OracleQi .
v$version, PL/SQL Oracle,
SQL*Plus:
SQL> SELECT * FROM v$version;
BANNER
Oracle9i Enterprise Edition Release 9 . 0 . 1 . 0 . 0 - Production
PL/SQL Release 9 . 0 . 1 . 0 . 0 - Production
CORE
9.0.1.0.0
Production
TNS for Solaris: Version 9 . 0 . 1 . 0 . 0 - Production
NLSRTL Version 9.0.1.0.0 - Production
, , Oracle 8.1.7, Solaris. 19 19 9.0.1, Solaris.
Windows NT,
Solaris.

Oracle
Oracle, .
, , , . , "Oracle Server Reference"

16

"OracleS Server Reference", "OracleS Server Reference" "OracleQ i Server


Reference" Oracle.


web- "" (www.lory-press.ru) :
.
web- Osborne/McGraw-Hill Oracle Press:
www.osborne.com.
. Development Tools (. 2).
, , readme, html, .


, ,
. ( web-)
cocfe, . , :
SimpleLoop.sql
DECLARE
v_LoopCounter BINARY_INTEGER := 1;
BEGIN
LOOP
INSERT INTO temp_table (num_col)
VALUES (v_LoopCounter);
v_LoopCounter := v_LoopCounter+ 1;
EXIT WHEN v_LoopCounter > 50;
END LOOP;
END;

code/ch01/SimpleLoop. sql.
code/readme, html .

,
, , ,
. : students (), classes (_) rooms (). , registered_students (_)
, .

SQL-, .

PL/SQL

17


tables, sql, code
"" : ww. lory-press, ru.

student__sequence students, room_sequence


rooms.

Q CREATE SEQUENCE student_sequence


START WITH 10000
INCREMENT BY 1;
CREATE SEQUENCE room_sequence
START WITH 20000
INCREMENT BY 1;
students
students ,
. ( id , f i r s t _ n a m e , last_name , m a j o r , c u r r e n t _ c r e d i t s .)
Q CREATE TABLE students
id
first_name
last_name
major
current_credits
);

(
NUMBER(5) PRIMARY KEY,
VARCHAR2(20),
VARCHAR2(20),
VARCHAR2(30),
NUMBER(3)

INSERT INTO students (id, first_name, last_name, major,


current_credits)
VALUES (student_sequence.NEXTVAL, 'Scott', 'Smith',
'Computer Science 1 , );
INSERT INTO students (id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Margaret', 'Mason',
'History', 4);
INSERT INTO students (id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Joanne', 'Junebug',
'Computer Science', 8);
INSERT INTO students (id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Manish', 'Murgratroid',

18

1
'Economies', 8);
INSERT INTO students(id, first_name, last_name, major,
current_credits)
VALUES(student_sequence.NEXTVAL, 'Patrick', 'Poll',
'History', 4);
INSERT INTO students(id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Timothy', 'Taller',
'History', 4);
INSERT INTO students(id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Barbara', 'Blues',
'Economies', 7);
INSERT INTO students(id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'David', 'Dinsmore',
'Music', 4);
INSERT INTO students(id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Ester', 'Elegant',
'Nutrition', 8);
INSERT INTO students(id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Rose', 'Riznit',
'Music', 7);
INSERT INTO students(id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Rita', 'Razmataz',
'Nutrition', 8);
INSERT INTO students(id, fir.st_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Shay', 'Shariatpanahy',
'Computer Science', 3);
major_stats
m a j o r _ s t a t s
. ( total_credits , total_students .)
CREATE TABLE major.stats (

major
VARCHAR2(30),
total.credits NUMBER,
total_students NUMBER);

INSERT INTO major_stats(major, total_credits, total_students)

PL/SQL

19

VALUES ('Computer Science', 22, 3);


INSERT INTO major_stats(major, total_credits, total_students)
VALUES ('History', 12, 3);
INSERT INTO major_stats(major, total_credits, total_students)
VALUES ('Economies', 15, 2);
INSERT INTO major_stats(major, total_credits, total_students)
VALUES ('Music', 11, 2);
INSERT INTO major_stats(major, total_credits, total_students)
VALUES ('Nutrition', 16, 2);

rooms
rooms . ( room_id , b u i l d i n g , room_number , number_seats , d e s c r i p t i o n .)
| CREATE TABLE rooms
room_id
building
room_number
number_seats
description
);

(
NUMBER(5) PRIMARY KEY,
VARCHAR2(15),
NUMBER(4),
NUMBER(4),
VARCHAR2(50)

INSERT INTO rooms (room_id, building, room_number, number_seats, description)


VALUES (room_sequence.NEXTVAL, 'Building?', 201, 1000, 'Large
Lecture Hall');
INSERT INTO rooms (room_id, building, room_number, number_seats, description)
VALUES (room_sequence.NEXTVAL, 'Building 6 ' , 101, 500, 'Small
Lecture Hall');
INSERT INTO rooms (room_id, building, room_number, number_seats, description)
VALUES (room_sequence.NEXTVAL, 'Building 6 ' , 150, 50, 'Discussion Room A ' ) ;
INSERT INTO rooms (room_id, building, room_number, number_seats, description)
VALUES (room_sequence.NEXTVAL, 'Building 6 ' , 160, 50, 'Discussion Room B ' ) ;
INSERT INTO rooms (room_id, building, room_number, number_seats, description)
VALUES (room_sequence.NEXTVAL, 'Building 6 ' , 170, 50, 'Discussion Room C ' ) ;
INSERT INTO rooms (room_id, building, room_number, number_seats, description)
VALUES (room_sequence.NEXTVAL, 'Music Building', 100, 10, 'Music
Practice Room');
INSERT INTO rooms (room_id, building, room_number, number_seats, description)
VALUES (room_sequence.NEXTVAL, 'Music Building', 200, 1000, 'Concert Room');
INSERT INTO rooms (room_id, building, room_number, number_seats, description)
VALUES (room_sequence.NEXTVAL, 'Building 7 ' , 300, 75, 'Discussion Room D ' ) ;
INSERT INTO rooms (room_id, building, room_number, number_seats, description)

20

VALUES (room_sequence.NEXTVAL, 'Building 7 ' , 310, 50, 'Discussion Room E - ) ;

classes
classes , . ( department , course , max_students
, current_students , num_credits .)
) CREATE TABLE classes (
department
CHAR.(3),
course
NUMBER(3),
description
VARCHAR2(2000),
max_students
NUMBER(3),
current_students
NUMBER(3),
num_credits
NUMBER(1),. .
room_id
NUMBER(5),
CONSTRAINT classes_department_course
PRIMARY KEY (department, course),
CONSTRAINT classes_room_id
FOREIGN KEY (room_id) REFERENCES rooms (room_id)
);
INSERT INTO classes(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES ('HIS', 101, 'History 101', 30, 11, 4, 20000);
INSERT INTO classes(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES ('HIS', 301, 'History 30V, 30, 0, 4, 20004);
INSERT INTO classes(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES C C S ' , 101, 'Computer Science 101', 50, 0, 4, 20001);
INSERT INTO classes(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES ('ECN 1 , 203, 'Economics 203', 15, 0, 3, 20002);
INSERT INTO classes(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES ( ' C S ' , 102, 'Computer Science 102', 35, 3, 4, 20003);
INSERT INTO classes(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES ('MUS', 410, ''Music 410', 5, 4, 3, 20005);
INSERT INTO classes(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES ( ' E C N ' , 101, 'Economics 101', 50, 0, 4, 20007);
INSERT INTO classesCdepartment, course, description, max_students,
current_students, num_credits, room_id)
VALUES NUT 1 , 307, 'Nutrition 307', 20, 2, 4, 20008);

PL/SQL

21

INSERT INTO classes(department, course, description, max_students,


current_students, num_credits, room_id)
VALUES ( ' M U S ' , 100, 'Music 100', 100, 0, 3, NULL);

registered_students
registered_students ,
. ( student_id , g rade .)
)

CREATE TABLE registered_students (

student_id NUMBER(5)
NOT NULL,
department
CHAR(3)
NOT NULL,
course
NUMBER(3)
NOT NULL,
grade
CHAR(1),
CONSTRAINT rs_grade
CHECK (grade I N ( ' ' , ' ' , ' C ' , ' D ' , ' ' ) ) ,
CONSTRAINT rs_student_id
FOREIGN KEY (student_id) REFERENCES students (id),
CONSTRAINT rs_department_course
FOREIGN KEY (department, course)
REFERENCES classes (department, course)
);
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10000, - C S ' , 102, ' A ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10002, ' C S ' , 102, ' B ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10003, 'CS:, 102, ' C ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10000, 'HIS', 101, ' A ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10001, 'HIS', 101, ' B ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10002, 'HIS', 101, ' B ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10003, 'HIS', 101, ' A ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10004, 'HIS', 101, ' C ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10005, 'HIS', 101, ' C ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10006, 'HIS', 101, ' ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)

22

VALUES (10007, 'HIS', 101, ' ' ) ;


INSERT INTO registerecLstudents (student_id, department, course, grade)
VALUES (10008, 'HIS', 101, ' A ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10009, 'HIS', 101, ' D ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10010, 'HIS', 101, ' A ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10008, 'NUT', 307, ' A ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10010, ' N U T ' , 307, ' A ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10009, ' M U S ' , 410, ' B ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10006, ' M U S ' , 410, ' E ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10011, ' M U S ' , 410, ' B ' ) ;
INSERT INTO registered_students (student_id, department, course, grade)
VALUES (10000, ' M U S ' , 410, ' B ' ) ;

RS_audit
RS_audit , registered_students. ( change_type , changed_by , timestamp , o l d _ s t u d e n t _ i d
, old_department , old_course
, old_grade , new_student_id
, new_department , new_course
, new_grade .)
[J CREATE TABLE RS_audit (

change_type
changed_by
timestamp
old_student__id
old_department
old_course
old_grade
new_student__id
new_department
new_course
new_grade

CHAR(1)
NOT NULL,
VARCHAR2(8) NOT NULL,
DATE
NOT NULL,
NUMBER(5),
CHAR(3),
NUMBER(3),
CHAR(1),
NUMBER(5),
CHAR(3),
NUMBER(3),
CHAR(1)

PL/SQL

23

log_table
log_table Oracle. ( code , message , i n f o .)
)

CREATE TABLE log_table (


code
NUMBER,
message
VARCHAR2(200),

info
);

VARCHAR2(100)

temp_table
temp_table . (
num_col , char_col .)
Q CREATE TABLE terap_table (
num_col NUMBER,
char_col VARCHAR2(60)

);

books, class_material library_catalog


books, class_material library_catalog
, . (. 8).

PL/SQL,
. ,
PL/SQL , , . ,
. PL/SQL 3.

26

* PL/SQL , .
,
PL/SQL. ,
PL/SQL, Oracle
.

PL/SQL
, ,
:
, . .
, .
,
.

.
PL/SQL, PL/SQL. Java,
PL/SQL (PL/SQL engine) . ,
Oracle , PL/SQL
,
PL/SQL .


, /, .
: . , . .
, .

PL/SQL
Oracle 6, PL/SQL ,

PL/SQL.
SQL, , SQL-, PL/SQL. , : Oracle
, SQL-,

27

PL/SQL. , SQL-
PL/SQL
SQL, , SQL*Plus.
SQL*Plus. SQL>, a SQL*Plus .
, SQL*Plus.
PL/SQL SQL, CREATE OR REPLACE PROCEDURE.
SQL_PLSQL.sql
SQL> CREATE OR REPLACE PROCEDURE ServerProcedure AS
2 BEGIN
3
NULL;

4 END ServerProcedure;
5 /

Procedure created.
SQL> DECLARE
2
v_StudentRecord students%ROWTYPE;
3 v_Counter BINARY_INTEGER;
4 BEGIN
5 v_Counter := 7;
6
7 SELECT *
H
INTO v_StudentRecord
9
FROM students
10
WHERE id = 10001;

11

12

13

ServerProcedure;

14 END;

15 /
PL/SQL procedure successfully completed.
SQL> UPDATE classes
2
SET max_students = 70
3
WHERE department = 'HIS'
4 AND course = 101;
1 row updated.

, ,
"" : mw. lory-press, ru.
"- -
_aa.sql". ,
,
readme.html code.

28

. 2.1. (
SQL*Plus) PL/SQL (
, SQL-, ) SQL-. SQL- SQL-,
PL/SQL PL/SQL, . PL/SQL (,
), SQL- (,
SELECT) SQL-.

DECLARE
v_StudentRecord students%ROWTYPE;
v_Counter BINARY_INTEGER;
BEGIN
v_Counter := 7;
SELECT *
INTO v_StudentRecord
FROM students
WHERE id = 10001;

UPDATE classes
SET max_students = 70
WHERE department = 'HIS'
AND course =101;

Serve rProcedureQ;
END;




PL/SQL

(
)


PL/SQL
SQL-
PL/SQL

PL/SQL

SQL-


PL/SQL

SQL-
Oracle

. 2.1. PL/SQL

SQL-,
,

SQL-

29

, PL/SQL,
PL/SQL , . ( Pro*C, JDBC, OCI
)
SQL, PL/SQL. , PL/SQL
, SQL, .
PL/SQL
Oracle.

PL/SQL
PL/SQL, ,
Oracle (Forms Reports) PL/SQL. , croporfe .
PL/SQL. PL/SQL, PL/SQL .
PL/SQL , . PL/SQL ,
. , Oracle
Forms .
, SQL- .
PL/SQL, (. 2.2).
, SQL-,
( UPDATE), , SQL- . PL/SQL . (,
) , . SQL- PL/SQL (, SELECT) ,
PL/SQL.
ORACLE Oracle, */++
Pro*COBOL, ,
PL/SQL . PL/SQL. , SQL-,
PL/SQL-, ,
.
PL/SQL.

.
Oracle.

30


DECLARE

v_StudentRecord students%ROWTYPE;

v_Counter BINARY_INTEGER;
BEGIN
v_Counter := 7;

UPDATE classes
SET max_students = 7 0
WHERE department = 'HIS'
AND course = 101;

SELECT *
INTO v_StudentRecord
FROM students
WHERE id = 10001;
ServerProcedure();

END;


PL/SQL




PL/SQL,




PL/SQL

PL/SQL
SQL-
PL/SQL

PL/SQL

SQL-

SQL-,
,

SQL-


PL/SQL

SQL-
Oracle

. 2.2. PL/SQL

. 2.2 PL/SQL, . , ( PL/SQL)
( PL/SQL).

31

(RFC, remote procedure


calls). PL/SQL, , .
PL/SQL
. PL/SQL ,
(. 10).


, . , , ""; , , -. ,
, . PL/SQL
. , ,
,
, . ,
, .
Oracle Internet Application Server (IAS) . PL/SQL

.Web-
PL/SQL




HTML


PL/SQL

\
4

\
**

Oracle

/
PL/SQL


PL/SQL
SQL-

. 2.3.

SQL-

32

,
HTML-. web- PL/SQL (PL/SQL Web Toolkit), IAS (. 2.3).
web- PL/SQL Oracle.

Oracle9i Forms Reports


,
- .


, PL/SQL ( SQL)
. , .
, ,
.
PL/SQL
. ,
PL/SQL. , SQL*Plus connect. (. ).
PL/ SQL.
( ), (,
Oracle Forms) PL/SQL
.


PL/SQL
, PL/SQL, .
, 2.1. ,
SQL*Plus Oracle , . "" : www. lory-press, ru.

Development
Tools.
readme, html .

33

2.1. PL/SQL

SQL*Plus

Oracle Corporation

www.oracle.com


""

Rapid SQL

Embarcadero
Technologies

www.embarcadero.com

DBPartner

Compuware

www.compuware.com

SQL Navigator

Quest Software

www.quest.com

TOAD

Quest Software

Www.quest.com
www.toadsoft.com

www.bmc.com

SQL-Programmer BMC Software


PL/SQL Developer

Web-

Allround Authomations www.allroundautomations.nl

, ,
PL/SQL.
Windows
NT, 19 Solaris.
(. 1) PL/SQL Java. , .
setup, sql.

,
,

AddNewStudent

AlmostFull
ModeTest
ClassPackage
Point
SimpleClass


Java


tables.sql
ch09/AddNewStudent.sql
ch09/AlmostFull.sql
ch09/ModeTest.sql
ch09/ClassPackage.sql
ch12/Point.sql
ch02/SimpleClass

SQL'Plus
SQL*Plus, , PL/SQL. SQL- PL/SQL .
,
. ,
PL/SQL .

34

SQL*Plus Oracle Oracle.


SQL*Plus "SQL*Plus User's Guide
and Reference".
SQL*Plus . ,
:
SQl> VARIABLE v_Nimi NUMBER

SQL> variable v_Char char(3)


SQL> vaRIAbLe v_Varchar VarCHAR2(5)

SQL*Plus , Windows GUI.


SQL*Plus, . UNIX SQL*Plus GUI.
19 SQL*Plus,
. , iSQL*Plus, SQL>
, . iSQL*Plus, Windows, GUI (,
), , , .
iSQL*Plus
Oracle.


SQL*Plus - SQL PL/SQL .
:
(, , ) SQL*Plus
connect SQL*Plus
( Windows iSQL*Plus)
, , , Log On
, ,
SQL*Plus , . Windows Log On . 2.4.
$ sqlplus example/example
SQL*Plus: Release 9 . 0 . 1 , 0 . 0 - Production on Tue Oct 9 16:32:22 2001
(c) Copyright 2001 Oracle Corporation. All rights reserved.
Connected to:
Oracle9i Enterprise Edition Release 9 . 0 . 1 , 0 . 0 - Production
With the Partitioning option
JServer Release 9 . 0 . 1 . 0 . 0 - Production

35

SQL> exit
Disconnected from Oracle9i Enterprise Edition Release 9.0.1.0,0 - Production
With the Partitioning option
JServer Release 9.0.1.0.0 - Production
$ sqlplus example
SQL*Plus: Release 9.0.1.0.0 - Production on Tue Oct 9 16:33:23 2001
(c) Copyright 2001 Oracle Corporation. All'rights reserved.
Enter password:
Connected to:
Oracle9i Enterprise Edition Release 9.0.1.0.0 - Production
With the Partitioning option
JServer Release 9.0.1.0.0 - Production
SQL> connect example/example
Connected.
SQL> connect exanple/example@v806_tcp
Connected.

User Name:
Password:
Host String:
OK

Cancel

. 2.4. SQL*Plus Log On


SQL PL/SQL
SQL*PLus SQL>. SQL PL/SQL .
SQL*Plus (, set s e r v e r o u t p u t
on, . ). SQL*Plus
( (forward slash)) SQL-.
. SQL*Plus , ,
, . PL/SQL
, . DECLARE
BEGIN SQL*Plus , PL/SQL, SQL- . SQL*Plus
, . , RUN SQL*Plus. SQL*Plus
PL/SQL , run
SQL*Plus.

36

. 2.5 PL/SQL SQL. PL/SQL, registered_students. SELECT, ,


, (
SQL- ). ( "successfully
completed") SELECT ( ).

0 dk Search JJpfore Help


SQL> DECLARE
2
CURSOR c_Music410Students IS
3
SELECT *

ii
5
6
7
8
9
10
11
12
13
14

FROM registered_students
WHERE department - 'MUS1 AND course = 4
FOR UPDATE OF grade;
BEGIN
FOR c_Student IN c_Music410Students LOOP
UPDATE registered_students
SET grade - 'a 1
WHERE CURRENT OF Music41Students;
END LOOP;
END;
/

PL/SQL procedure successfully conpleted.


SQL>
2
3

SELECT
FROM registered_students
WHERE department - 'MUS 1 course - 41B;

STUDENT ID DEP
10009
1B006
10011
10000

MUS
MUS
MUS
MUS

COURSE G
lt1B
410
410
410

ft

SQL>

. 2.5. PL/SQL SQL'Plus


SQL*Plus PL/SQL SQL , . , PL/SQL,
. , CREATE OR
REPLACE, ,
. SQL*Plus. .
start, SQL*Plus, (
19 Web URL). , , , . @
start. , F i l e . s q l :
Q - File.sql
BEGIN

37

FOR v_Count IN 1. .10 LOOP


INSERT INTO temp_Table (num_col, char_col)
VALUES (v_Count, 'Hello World! ');
END LOOP;
END;

SELECT * FROM temp_table;


SQL:
SQL> @File
. 2.6. set echo on
( ) SQL*Plus,
.
Jfc Oracle SQL-Plu
* Search Options Help
SQL> set echo on
SQL> Qch02\File
SQL> BEGIN
2
FOR u_Count IN 1..10 LOOP
3
INSERT INTO temp_table (nun_col, char_col)
4
UflLIJFS (u_Count, 'Hello World! 1 );
5
END LOOP;

_d

6 END;
7

PL/SQL procedure successfully completed.


SQL>
SQL> SELECT FROM tetnp_table;
NUM_COL CHflR COL
1
2
3
i|
5
6
7
8
9
10

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello

World!
World!
World!
World!
World!
World!
World!
World!
World!
World!

10 rows selected.

J
. 2.6.

,
.
DBMS_OUTPUT
PL/SQL /. UTL_FILE
(. 12) ,

38

, . ,
SOJL*Plus DBMS_OUTPUT . :
1. SQL*Plus set
serveroutput. :
SETSERVEROUTPUT{ON|OFF} [SIZE n]
. n , 2000 . 1 000 000
. ON OFF .
2. PL/SQL DBMS_OUTPUT.PUT_
LINE, .
SQL*Plus
.
DBMS_OUTPUT.PUT_LINE. SQL*Plus , SQL*Plus, .. .

DBMS_OUTPUTn UTL_FILE .

9 10,
, .
. 2.7 DBMS_OUTPUT.PUT_
LINE.
, Oiacle SQL'Plus
file
SQL>
SQL>
2
3
1
5
6

Edit

Search flptions Help

SET SERUEROUTPUT ON SIZE 10B0000


BEGIN
DBMS_OUTPUT.PUT_LINE('Hello from PL/SQL!');
DBMS_OUTPUT.PUT_LINE('Today is ' ||
TO_CHflR(SVSDflTE, 'DD-MON-VVVV));
END;
/

Hello from PL/SQL!


Today is 26-OCT-2001

PL/SQL procedure successfully completed.


SQL>

J
11

. 2.7. DBMS OUTPUT

39

Rapid SQL
Rapid SQL Embarcadero Technologies
.
:

PL/SQL SQL
PL/SQL
Java OracleS i
PL/SQL
SQL


Windows Active Scripting
,

Rapid
SQL .

Rapid SQL , ,
. 2.8.
file Qatasource froiect growse
jiSsl S. ;:!;

Lpgtile View Joels Help

!| !|1|18 Selected)

ftfffe'u;'*!-*'|-jif

Oracle Servers
Gal V817 (Oracle 8.1.7.0.0)
gll V901 (Oracle 3.0.1.0.0)

1>|
0

IBFavorilts

1:36:14PM Program Using Datasource Catalog on Local Comput


1:616 Program DB2kno/tedae modufeloaded
1:6:16 Program OS3SC knowledge module loaded
1:3S:18 PM Program Oracle knowledge module loaded
1:36:23PM Program SQL Server knowledge module loaded
) A WF

{Catalog: Local

. 2.8. Rapid SQL

{Workspace 1

NUM ;iNS

40

, .
, . (datasource) ,
: ,
, .
Rapid SQL , SQL*Net .
, (. . 2.9).
Datasource.
Login to V301
Login id:
[example
Password:

Cancel

. 2.9.

, Rapid SQL , . .

SQL PL/SQL
SQL- PL/SQL
SQL. SQL File | New | SQL.
SQL PL/SQL ( /),
SQL. , Execute (. . 2.10).
Results (. . 2.11). PL/SQL (, ) SQL. DBMS_OUTPUT.PUT_LINE
.


Rapid SQL ,
PL/SQL. , Rapid
SQL ,
, .

41

**. Rapid $Qt 57.1

[SQL 1 -J

]E] Ete

Browse

Edit QatasoufCe

Project

LogWe Vew flue lafc tfrcSow Help

fit* :t met ilasvaoi (oiadei

ju

-UJxl

ii

_jj!j%Bin 3><5 e'ijj&-<*

Q i c S a j P ^ s a i d - j i I I L^ ^h*fe@4i>O^'S.j,?i^ [-! tfifti 4 !


jpstt**iP!< : .^,,>rf,? jjja a t *!|*^.|**%| / *-4;% > !
El ^ ^&

"!^^

6:3 Managed Datasource!

V817

^S
i|-"*J*
ft-
'fj-*^
-
fW

DECLASE
R Husic410Students 12
SSL *
IROH regisCcred_students
i
J OR UPDATE OF grade;
BEGIH
FOR Student IS Hus i 410 Students LOOP
UPDATE registered students
1
0
5 IT grade - 'li
1
JERE COWEIT OF Hu3ic4103tudents;
2
LOOP;
3 OD;
4 /
S
6 SELECT * TROH registered^students
7
departnent *(' ASD course - 410;

OL0

1&^

FundlOm

ift-
-{>
i^-^'
$-j|^
4-21
-W
4^
S-^

Indexes
Java Classes
JavaSouces
Java Resources
Uxaries
Packages
PLVSQlCodePtofiJing
Primary Keys
Piocedutet

i|rft
'
-''
-.
:*?

Roles
Rofcack Segments
Sequences
HateiiaEzedViews(5napshot
MatenaizedVieMLogslSnaF*

.1

iectoai

f
- '
Check Constraints
Oustes
Database LJnki
DiKloie.
FcxeignKeys

^T

9
0
1
2

BEGIH
DBHS_ OUTPuT.PTJT LIHE('Kello froa PL./KOL!'); .
DBHS"OUTPUT. PUTJ-IHEt1 Today is ' | 1
^-', ' D&-HOH-nTY ' ) J ;

LLU

J
jVSOlVeiiropie

xecuteSQLttatemnts

jVSOIVenamdle
ICaiakS'Eocal

Lira 24 Col 4
jWcSsiace'l" \

6 Ron(si (
(NUM'jiNS'^s

. 2.10. SQL

Ffc < Foimat

View Tool. Wndow Help

>

E
^Jxt
.l*PlgL'-lg Object Type...
M raged Dataiaicet
l Oracle Sefveit
- Vfl17(0radeat.7.0.0)
f^ Check Conttieinti
- Qutte
ff^i Database Links
-W
VA
-gp
'
*K^

ForgnKeys
Funcbons
Indexes
-JavaOassci
JavaSouice*

il |
ji-'W
L*'-Q,
/
f-ITi
fr^
fft
i>-Al
i-'2$

Lbtviet
Peckege*
PL/SQL Code Piofifcig
PrimetyKay.
Pioceduret
PioBe
Ftofei
Rofcack Segments
Sequences

la,
The command executed successfully win no resuts returned.
'_

STUDEHT ID .......

!DARti.4r|cO.JRSEfcRAMf
MUS
i410
\A

-js'" ...... "":4ib X


MUS" ........ " ..... iib' .......... |X

idobe'

10011

VOOOO "

'MUS ............ J41 0 ..... A

DBHS Output for Batch 3


1 Heto 1 rom PUSQLJ
1 Today is 26-OCT -2001

; Waioff'Lociii

. 2.11. Results

'wurkspaceT ; .......... jNUM'jiNS"

42

2

.
. AlmostFull
. 2.12.
fatf;w-A<ftfff*rp/tf$ffl 571

[U file rA Qatasgurce Eroiect

fXAMPLE E I J00080046I1001 l|

Q i cS H ! S a i "

l * j|tB ^ E i 0 . l ^ 9 l * f e @ % i S ? ' & $* \\\ m, .f &f ]

\ j SQ w | ^ ' : f: ^ H^ ^ ^ v . H i - M t f ^ j x i ^ ^ ^

P % tl >t flagj ] a? ,-e


^_JiJ

CRSATE GR REPLACE FUHCT10K EXAMPLE. AlttOStFUll (


p_Departent classes. depaturienMTfPE,
BOOLEAN IS

5
6
7
8
9
10

u_CurrentStudents HUHBSR;
v_Hax Students
UUHBER;
v_Re CurnVal ue
EOO LEAH ;
v_rullPercent
COK3TAHT SOMBER :- 80;
BEGIH

12
-- course.
13 SELECT cutrent_student3, ax__studenta
14
IMTO v_Current3tudents, v_Hax3tudents
15
FROE classes
16
VHEPZ deparcmenc = p_Depactment,
17
) course p Course;

'- Privileges
4 Indexes
& Javfl Classes
^ Java Sources

MamelValuel

J9 i1* tf s1 1 i * 0 ! ^ i& 1 I *i
1
2

- Functions (1)
| - EXAMPLEALMOSTFUL

~l3l x|

j B% s ffl"^^?f [j|> '0 9*

jj |f

| ft Si | jj?>* ||aSv301 (Orade

Explorer -By Object Type


tjj Managed Datasources
3-3 Orade Servers
4-86 V81 7 (Oracle 8.1. 7.0.0I
e|Si V901(Crde9. 0.1.0.0)
- Check Constraints
\f& !
'% Database Links
-L^ Directoriei

HHE3I

Debug firowse Logfite yiew Query loots Window Help

MJ

^T
:

jVSCri'^'ample

Type
_y_

jj

Name
|Valiicl
!Su!.rWkje__!NyU-jBgpLE
Louise
llbT
CLASS!

-5J EXAMPLE.ALMOSTFULL{)Ur,e:
*
41.008060001{

i^^^SIl'NOENiBP Department 7HIS


CtASSI.

iL ""T"

""

"T 1 .1

ear*.

" ftineTs Col'l

"'

!ORow(si

fljjj'

Name
Tf 3| Dependences
L-pg FXAMPLE FTSflnnfltrMfimn
U/

" EX4MPLE.ALMOSTFULL

[Catalog Loc5~"~

i
Voi'kspace 1 ' ;

JNUM'JNS

/f

. 2.12. Rapid SQL

Rapid SQL
, Rapid SQL
:
.
.
; ,
.
PL/SQL.
, PL/SQL, , . ,
.
PL/SQL. PL/SQL (OracleSz ) PL/SQL. Rapid SQL GUI-
,
.

43

.
. email.
. , .
SQL PL/SQL, HTML Java.
. DDL SQL
.
. .

DBPartner Debugger
DBPartner Debugger Compuware Corporation. , :
SQL PL/ SQL
PL/SQL Java
Java OracleS



DBPartner Debugger DBPartner. SQL Tuner Viewer. DBParner Debugger
.


DBPartner Debugger . ,
. "userid/password",
. . 2.13.
.
DBPartner Debugger, . , , DBPartner
Debugger. (Database
Setup Wizard),- . 2.14. , . Database |
Setup Wizard. DBA,
. DBA .

44

DBPailnei Debugger (01 Oracle Login


DB Profile:

|V901.US.ORACLE.COM/exajj|

- ORACLE
Server

QcQpnect J

1
JV901.US.ORACLE.COM J

Cancel
Save

(EXAMPLE

Delete

Password:

Default

-DBPattriei OebuggeiLbec

Help

. 2.13. DBPartner Debugger


DBPaitner Debugger DB Setup
This wizard will guide you through the
DBPartner Debugger database setup
process.
Please choose one of the following:

(t Install / upgrade
Uninstal

C" Manage users

Help

Next

Cancel

. 2.14.

SQL PL/SQL
SQL PL/SQL SQL Notepad, File | New SQL Notepad . SQL Notepad PL/SQL ( /),
SQL. SQL Notepad
Execute (. . 2.15).
SQL SQL Output (. . 2.15). DBMS_OUTPUT.PUT_LINE
DBMS Output SDL Notepad (. . 2.16).

45

Efc Ed 'Database labfc Uprnn Khdo Help

?i ^-^j
* ^ ?--' .
&- i' ss ' ss* .' ra1 : P - '
1

7 ji"{" '

|g 581 HottqMtd JM - V W l !!', r i R V j r fiLXAMF'Lf: }


FOR Student IH Kusic^lDStudents LOOP
UPDATE registered students
SET grade - ' A '
WHERE CURRENT Of c_Hu9ie410Studenta;
END LOOP;

.01 Uulput 2 |V90I US ORACLE COM |E


Student Id Department

Course

Gl

Grade

''.^^^..
10000 MUS
10006MUS
10009MUS

BHD;

SELECT
FROM registered students
WHERE department - 'HITS' JUTD course - -Ku;

410A
410A
410A

BEGIH
DBH3_OUTPOT.PyT_LIME('Hello l'ra PL/ SQL ! ' ) .DBKS^OUTPOT.PUT^INECToday 1* ' ||
1
TO CHAR(SYSAATK, ' DD-HCW-YYYY ] ) ;

OperetionLog j DBMS Output j SQLEiiori

Line: 16 Selected rows e letrieved a needed.


Line: 20 Fb^QLpfocedur ewes completed tuccewfu-V-

26:1

Rii*

j
A

. 2.15. SQL Notepad


OpeefonLog DBMS Output | SQL Enort j
Hefa from PL/SQL)
Today i* 26-OCT-2001

. 2.16. DBMS Output


DBPartner Debugger PL/SQL . File | New Debugger
Debug. , DBPartner Debugger
. . 2.17.
PL/SQL, DBPartner Debugger
Java- (18 ). Java-, PL/SQL, .
DBPartner Debugger. Java
. 2.18.

46

Eto dt Database
'
_.._ . . .

"Help

"

Qobuff Qpfor*

S&OBPailner Debuggei - EXAMPLE ALMUSTFULL


Status: (& Connected to: V901.IJS.ORACLE.COM (EXAMF1E)
0010

BEGIM

0011

0012
0013

1.

,-

^ii-r^V.

J=Tid

1-.|

*3^

'-se.
SELECT current students, tnax_atudencs
FROM classes
WHERE department - p__Departioent
8 - p_Course;

0015
0016
0017
Li l.' I H
Dij !'J

0020
0022
0023
0024

v_HeturnValue :=> TRUE;


ELSE
v ReturnValue :- FALSE;

\&f ^Department classes, department^ TYPE


6-s &f p.Department

.EXAMPLE ALMOST FULL


[EXAMPLE ALMOST FULL

UlO
[<NUL

s tftf* p_Coure daKesif Af p Couse NUMBEF1


!
"tS>410
}'6V v.CurentStudontt NUMBER
:. AT v.MacStudents NUMBER
- iftf v RftturiVakje BQOLEAM

;EXAMPLE.ALMOSTFULL

js>|

. 2.17. PL/SQL

" "

Edit Det^jase Qebug fiption* Wndow t[dp

e|rel>i
SMUK J&

Connected to; V901.US.ORACLE.COM [EXAMPLE)

0001 class SimplcClass


0002
{
0003
static public void Hello ()
0004
{
0006
0007

III...

v ^j Hdlo d(!
* U <inb

type

J _ Name

V.ywe

Vatiable SB ] Enpten fe | Lcckrg $| Bieakpoinls || Slack ^|saon jfe. | DBMS

. 2.18. Java

47

DBPartner Debugger ,
. , , . , SQL PL/SQL
, , DBPartner Debugger.

DBPartner Debugger
, DBPartner Debugger
:
. , .
, . .
. , . DBPartner Debugger
SQL /. SQL
SQL, PL/SQL
Java.
PL/SQL. , PL/SQL,
, .
, .
.

.
.
SQL.
. DBPartner :
SQL Tuner,
SQL, ; SQL Viewer, SQL PL/SQL
.

SQL Navigator
SQL Navigator Quest Software.
,
:
PL/SQL SQL
PL/SQL
()

48

OracleS OracleS



DBPartner Debugger, SQL Navigator . ,
. , , . 2.19.
,
. SQL Navigator .
Connect to Database
Connection Prof

OK

JV901 - EXAMPLE

Cancel

Delete

Username: EXAMPLE
Password: "

I"'

'
Connect String: |V901
. 2.19. SQL Navigator
BQL Navigator Seiver Side Installation

Welcome to the SQL Navigator


Server Side Installation Wizard
This Wizard will install or remove server side objects for
use by SQL Navigator.

< Install Server Side Objects


Remove Server Side Objects

To begin, click Next

Next

llmllifmiirilliiniiTii

. 2.20.

|K
i"ni

Cancel

49

SQL Navigator ,
SQLNAV. (Server Side Installation Wizard) .
,
Tools | Server Side Installation Wizard.
, ,
SQL Navigator Tuner. . 2.20 .
SQL PL/SQL
SQL PL/SQL SQL.
, . PL/SQL, , /.
(
SQL*Plus).
. . 2.21 SQL
.
( ),
SQL PL/SQL.
DBMS_OUTPUT.PUT_LINE
Server Output ON Tools [ Server
Fte

Sich Yisw Eebug Iol

:j.,t|v90!

EEi E-
\\ Interval: [2 ^C] j
lyC SQL EdilM-VSOl EXAMPLE:! File:UnNamedl
Single SQL

SQL Script

***

* HI

&

DECLAKE
CURSOR c_Husic4iOScudencs I2
SELECT '
TR9K cegiscered_3tudent3
WHERE department - ! H U ' 1; course UP DATS: OF grade;
BEGIH
FOR c_Student IH c_Huaic410Scudents L*X!P
UPPATE regiscered_students
SET grade ' A 1
UHEPE CURRENT OF c_Husic4103tudents;
EKD LOOP;

END;

SELECT '
FROH registered students

[Processing

ID DEP COURSE
IJ10009
||l0006

HUS 410
HDS 410
(fop:! ""

. 2.21. SQL Editor

JByteT584"

|inSBrt

50

b Edit Beach View Debug look Wixiow Hdp

**i

jjifi l,S *J jS @] ,~S ji II w=fvat|2 Jj

StxfcSO.

,41*?!

;,, | " <| -,- |/|

SOLScript

S' ?
SET grade = ' A '
HERE CUSKEMT Of c_Husic410Student=;
EMU LOOP;
END;

SELECT '*
FROM registered_3tudent3
1
!
HERE depaccmeni: - - R U S course "
BEGIN
DBHS_OUTPUT.PUT_LIHE!'H^lJo Stow PL/'SC
DBHS_OUTPUT.PUT_LINEi'Today is ' ! I
TO_CHAH i;3Y3DATE,
EHC;

4 rows retrieved
Processing ...
HeUo (ton PI/SQL!
Today is 26-OCT-2Q01
Statement processed
26: 1

'Wodilied

'Servet Output (ON) Cick to turn OfT

. 2.22. DBMS_OUTPUT.PUT_LINE

Output. DBMS_OUTPUT.PUT_LINE
(. . 2.22).


PL/SQL ,
Debug, Debug ON
Debug | PL/SQL Debugging.
, , . . 2.23.
SQL Navigator ^
PL/SQL. , DBMS_DEBUG , SQL Navigator .

SQL Navigator
, SQL Navigator :
PL/SQL. .
SQL Navigator; ,

51

I Function) V901-EXAMPLE:! - ALMOSTFULL

*,11*,1*,
f fte

Search

Eebug IDC*

ufcw

Help

tp! |

x.? "

% \A EXAMPLE

aeeJectf26-OCT5l 01"5:28 PM"


New

*4aij

Name:

|fl) ALMOSTFULL

*(|11:[5:44:3?

Revert j g a v e

| Agjkyi j

Status;'VALID Safe Edit

Ctose j

^ f^ (iff

delp

FROM classes
HERE department - p_Department
AHi: course -- p_Course;

v^FullPercs-nt; return . O t h e r w j s e , return ?AL:?K.


IF (v_CurrentStudents / v_Kax5tudents 100) >- v_FullPercent THEM
v_R=turnValus ;- TPUE;
ELSE
v_ReturnValus : FALSE;

1 if;

call staac

FETBRM v_RetuirnValue;
END A l m o s t F u l l ;

?
1

Lre 4] v_Result > AlmostFuUCMUS ,41

EXAMPLE ALMOSIFULL
Watches | Breakpoints j
v_FullPercent: 80
v_MoxStuder<s: 5
p_0epartment: MUS
p_Course: 410

iLJ
~ Ones: 29

" |fop1S

jAPt v2.4

Reached a new ine

. 2.23.

. .
.
. DB Navigator ,
(
, ).
. Java
SQL Navigator, DB Navigator.
.
, , , SQL, PL/SQL, , .
,
SQL .
.
, WHERE SELECT.
DML.

52

PL/SQL. PL/SQL
,
.
, , Oracle.
. Code Assistant, Tools,
PL/SQL SQL. Code Assistant,
, .
.
, SQL.

TOAD
TOAD (Tool for Oracle Application Developers
Oracle)
SQL Navigator, Quest Software .
, . . TOAD :
PL/SQL SQL
PL/SQL

OracleS OracleS

,

TOAD ,
. ,
.


TOAD . , . 2.24.
File | New Connection.
, , File | Close Connection.
.

53

0 AD S eivei Login Veision 7. 1 . 7. 21


Server

I User

V301.US.ORACLE.COM
VS17.US.ORACLE.COM
V901.US.ORAaE.COM
V901.US.OHAOE.COM

EXAMPLE/EXAMPLE
EXAMPLE
EXAMPLE
SYSTEM

<
1 Last Connect

10/26/2001 2:22:49 PM
10/14/2001 11:02:57PM
104/2001 6:08:12 PM
10/8/2001 5: 16: 52PM

Database:

( userOdatabase )

U9B1 .US.ORftCLE .COM

-I

Usei/Schema
EXOMPLE
Eassword
Shew connection options

SQL-Net Help

Qk

Cancel

. 2.24. TOAD

TOAD , , - , .
, .
.
SQL PL/SQL
SQL PL/SQL SQL.
SQL SQL
PL/SQL,
1 SQL-Window Deate Djiubase lools View DBA Detss Window Help

B .0 * i* a - <i 41 is -

>[XAMPLti2>V301.US ORACLE.COM/

i ^! "3 ; * I g1 - ^ : f*'
CURSOR c_Musi.c410Students 13
SELECT *
FKOM registered_students
WHERE departant ' AND course - 410
FOR UPDATE OF grade :
EEGIH
FOK o_Studcnt IH c_Husic410Studcnts LOOP
UPDATE registared_students
SET grade ' E\ '
HERE CDRBEHT OF c_Music4105tudents:
EHD LOOP.
ESD.
SELECT
FROM registered_students
I'HERE departnent K'jS AHD course 410;
| ExptaPlailAuKTracel DSMSOummj CodeSlatistia SaiplOilpul |

PL/SQL procedure successfully completed


SELECT *
FROH registeced_student3
WHERE departmenc - ' K U S ' AHD course - 110
STUDENT_ID DEPAKTHENT COURSE GRABE
10009 HUS
25: 2

410 A

|1@01.5. f :Scnp(

. 2.25. SQL

54

. , (. . 2.25). Script Output, .


.
SQL
DBMS_OUTPUT.PUT_LINE,
. SQL*Plus SET SERVEROUTPUT ON,
DBMS_OUTPUT.PUT_LINE DBMS Output.
. 2.26.
File Ed* find SQL-Window &eale lock Mew DBfi ufby; Help

^ 3*'~ El > % ^ * !*" - i i 4 ! H - i

1 fe F.XAMPI.F <SV9I)1 .US. ORACLE. COM/

X * OB Si D ^ -Si & | " r> | EC *< | * * I A l% l%


> BEGIN

DBMS OUTPUT. PUT IIHEt T.:ia je ' II


TO CHiEfSYSDATE. ' ?D-XOH-YV';T ' } j ;

EMD:
X

Data j Explain Plan ] Auto Trace DBMS Output j Code Statistics j Scipl Output ]

Hello from PL/SQL!


Today is 26--21

25 2

jEXAMPLE(!>V9m.US.ORACLE.COM i

[Script mas executed with 0 enors.

Commit is OFF i

,f.
4

. 2.26. DBMS_OUTPUT.PUT_LINE


Step Into
Debug | Step Into. Set Parameters. ,
,
.
, . . 2.27.

55

CREATE OR REPIaCE FUNCTION ^ (


p_Departent cl .3 ssu; s . departneatXTYFE ,
p Course
iassc;? . courseVTYPE )
RETUKH B001EM IS
v Current Students
v_MaxStudents
v ReturnValue
v FullPercant
BSGIH
.i

HUHBER;
NUH0ER ;
BG01EAH;
CONSTANT ' :- 8

TraceQut
Hat Execution
Add Breakpoint al * F5
Add Welch alCuisor
CM.F5
Evaluate/Modify

CtrkAlt+E

Watchet
DBMS Output

Ctri+Aln-W
**0

SELECT current_students ax_students


I v CurrentStudents, v MaxStudents
FROM
WHERE departaent - p_Department
AND course * p_Course
/? j

v_ReturnValue
ELSE
v ReturnValue
END IF;

TRUE;
FALSE;

RETURN v ReturnValue;
END Almostfull;

Break Points Watches | DBMS Output j

Expiesiion
p_Depaitrrer)t
.FulPeicM

MJS
BO

1 Break! Scope
Local
I ocal

I Dwne'

. 2.27. TOAD

TOAD
, TOAD
:
. TOAD :
.
, , . , , .
. .
OracleS .
. TOAD : SQL (. )
. SQL
SQL SQL,

, , . , ,
.
.

56

. TOAD
PL/SQL SQL .
DBA. TOAD , DBA.
/.

SQL-Programmer
SQL-Programmer, .
:
PL/SQL SQL
PL/SQL

OracleS OracleS

,


SQL-Programmer
.
V-'SQL Programmer by Soflwale Evaluation Edition - Login
etvei

Help

! ,j- Currently Connected Jo


Database Type | Version
Descrption
1 Platform
^Oracle
8.17
OracleSi Enterprise Edition Release 8.1. 7.0.0 -Production Solaris

1 Name
V817

| Connected as
EXAMPLE

1 Connect Server
3

|ofile:

JV901

Setter:

[vsoi

jj

Fipe:

| Oracle Database Server

.oginID:

jexample

~"\

Disconnect Server
Kxamsd

p Options

|
j

Connect

|>IIKXI

!:

Sh:

3tiom:

f^terii)

P nabto Single Logon

. 2.28. SQL-Programmer

Done

5?

. 2.28. , .
.
SQL PL/SQL
SQL-Programmer PL/SQL. ,
SPDW ( SQL-Programmer). SPDW
.
, . 2.29 AddNewStudent SPDW. SQL PL/SQL.
, , ,
, .
.
!' file Edit Vie w PDW P_efai;g T.ocfs Windows Help

^.=r-iiira,:iiiS5SisBeilSEXAMPLE.ADDNEW5TUDEHI V90I - OFWCIESEBVEB Procedure (EnislinU

! x s ; e I

ADDNEWSTUDENT

-O Functions
Bj Piocedues
| | Ml ADDNEWS1
JMODETEST
SIMPLEV/R/
S6) UPOATECLT-1
IS -^ Packages
"& Objecl Types
^ Java Sources
J
if) dB Views
Tables
!

i> Clustets
- Materialized Vtew:
9 Materialized VievJ
^ff Sequences
*j
!

Edit

Ptoiogue

Epiogue

Argumenls

'

]1

' '

VALID

j Code Metrics |

Results

j Role Privileges! User Ptivyegesj

^-*-

pjlajor

students. jorXTVI'LJ fiS

INSERT

INTO students (ID, first_name, last_nane,


najor, current credits)
Uftl.lHIS (student sequence. nextval, p FirstName, p LastNanie
p^Major, (!);
EHD AddNeuStudent;

tT

Fie*
Favorkes

CodeFregs

To Do List
,'.

Module
<NctAveiable>

l,r,l

1
1 Statemer*
Debugger not running

sT
i ,: V/aich Variable

Vabe

|
=SS

tii'

! -1
*|5^ 2001-l6-Ufi550.4n ^82bytes l.ine:U ot.13 19 [Np Cnangtl U?er. EXAMPLE

MJM^INS SC--:. .EXAMPLE

. 2.27. SQL-Programmer

SPDW, , , . SQL-Programmer .
AddNewStudent . 2.30.
DBMS_OUTPUT.PUT_LINE,
( ) . Result SPDW,

58

Edit

Prologue

Name

p_FirstMame
p_LastName
p_Major

Epilogue

Arguments

] Code Metrics]

I In/Out
Type
students.first_n IH
students.last na IN
students.raajoritT) IN

Results

| User Privileges)

Execute Ualue
Chuck
Clmouly
Computer Science

Auditing

SjJ_t

Has Ualue
True
True
True

. 2.30. AddNewStudents


Step In
Debug | Step In. .
, . . 2.31
.

SQL-Programmer
, SQL-Programmer
:
. SQL-Explorer
, .
, SQL-Explorer
.
. ,
SPDW .

.
. SQL-Explorer
. Option.
. .

. ,
.

59

I 0e Edit View SPDW Jools ^imtowi Help

lilacS-aEM -;.: .<.. ' ^s>: ** i;f? : i - **. * ^-/*&< H:


exIS
. > a *;*1!-:' ;;:^ + *1^)|1*||*| *.***
l

n"Byj'mi^Ti:riKiianiMlllilHilili
Database Objects

.LMOSTFULL

2^1^1^11

^ G$ 5- ] X SJ S

Edit

:
:

j
!

Functions
ALMOSTFUI
- Procedures
i - S ADDNEWST
t -BlMODETEST
!
S SIMREWR/J

Ptdoaue

CurrentStudents
a ItexStudents
ReturnUalue
1> FullPercent
BEGIN

i- J. Object Types
-^ Java Sources

Epiogue

Arguments

Results

] Code Metrics j User Privileges j

ijj"i>auslei>

SB- Matela;edV"ewl.|

^j
HUNBEH;
HUMBLR;
001;
CONSTeHT NUMBER

:- 8;

' ^- i

-r

Fies

Favorites

I.I

Code Frags

IF (v CurrentStudents / u^MaxStudents 19S) >- u_FullPercent THEN


ReturnUalue := TRUE;
ELSE

.1
1

To Do List
7

Auditing J_Li.

SELECT current_students, nax_students


IHTO Current Students, MaxStudents
FBOM classes
WHERE department = p Department
flHD course = p_Course;

i - - Tables

RETURN BOOLEflN IS

.
1

Module

| Type

<*> EXAMPLE.ALMOSTFULL
.SQL-Piograrrme*

Function

| Statement

|^ Watch Variable
p_Coutse
[Lne21] IFJv_CuirentStudent
p_0eprjnent
<source not avaiablo
v.CutrentStuderts

| Value
41 0
MUS
4

|
^
i
11
j|

dlt

Remove

|il_

1 -Ulj,

Remove&l

Watches]

DebugginaFunctioniLaslSaveiZOul-IO^IS^^SlTSSbyleslUne:^ o(:29 Cot! JNo Change] ; User: EX4MR.E ;,:;:: :,, NUM. INS , :

J
]
J

EXAMPLE

. 2.3-1.

PL/SQL Developer

PL/SQL Developer Allround Authomations. :
PL/SQL SQL
PL/SQL

OracleS OracleS

( )
SQL*Plus

PL/SQL Developer . 2.32.
, .
,
. .

60

Oracle Logon

Username j example
1

Password """""

Database JV901.US.ORACLE.COM
Connect as [Notmal

OK

Cancel

. 2.32. PL/SQL Developer


, Session | Log.
PL/SQL Developer . 2.33. ,
.
pleG>V901. US. ORACLE. COM
te t Session

Qebug Jods Hacro

o; o* - . |

Documents itfndow

i -

EH

EH

+ - /
All obpcis
- Recent objects
_J Functions
' CJ Procedures
Q Packages
ffi Package botfes
ll Types
it Q Type bodies
CJ Triggers
C3 Java sources
CJ Libraries
Directories
CJ Tables
ffl CJ Viens
CJ Sequences
S6-CJ Us"

Rote.
* CJ Synonyms
BE Q Tablespaces
Ousters

$ -Cj Package elementr_li


S Q PL5QL Types
r: LJ Program units
_J

; J

fffl Packaoe

. 2.33.

SQL PL/SQL
SQL PL/SQL
PL/SQL Developer.
edit,
. SQL

61

SQL PL/SQL (
). SQL>, SQL*Plus.
SQL*Plus PL/SQL Developer. . 2.34 SQL .

Fife Edit

Cession Debug lods

fcjaao

Dgcuments ^indow

tt < - I ,

| <* % e i *. a * e e ; ^ * .
*'j>j&A|sse-s|?
< * - **!/

Al obiecls

B-ta Procedures
3
S ADDNEWSTL i
:
: Ei-<5) MODEIEST
i
- Paameter
; Cl Reference I
Refetence-J
! ' U3 Synonyms
! I S-CJ Granted Ic
! : ' Cl Granted EC
' SIMPLEWRAI
! & SYS.ODCICOl
It)- SYS.ODdEW
:
i ffl SYS.ODQIND
;
iS <D 3YS.ODOIND
f

SQL

.... daar

BUferstze [lOCOO

[^

|v Enabled

Hello fro PL/SOL!

Dialog

14

Editor ]

_d

SQL> SEbBCT *

STTJD1NT ID DRPAHTHIUT COURSE GRADB


'mm i3:1

SDoneindsee

avasource
Packaoe
-d
"'-fS
^ ''

S Program Window - Edit sod

1000 HUS

410 A

10011 HUS
10000 HU3

410 A
410 A

SQL> 21

~ SQL Wndow- BEGIN OS


Cornrriand Window Mew

^BHCll

Output | Statute* j

m nnrjiignd

ffi Package elementsd


- PLSQL THS
6-C3 Program units
_j
<^) Function
i

<J) ModeTest |

- >; w* ~ ill I;IN -; iinii'iiviaiT i imi-urii

SSjF:^- iTRM FOB

"'. APR .HDG fi'M ;PL/SQL procedure success!* c;CTnp!eted in 0.01 se-^J

. 2.34.

DBMS_OUTPUT.PUT_LINE
Output SQL .

.
.
Start Debugging. , ,
. . 2.35 .
PL/SQL Developer
, PL/SQL Developer :
.
.
, .

62

*^-:1

nle@V301. US. ORACLE. COM

File di Cession ebug look

-
" - /

Al objects

Macro

- _J Functions
.1
' - ALMOSTFULL I
' iti-Cj Parameter 1
\ iS"Cj Reference
i 'ii-Q Reference
: Cj Synonjms

Help

fin

a &

3 Test Windo -Sciiplloi function ALMOSTFULLPVSOI.US.ORftCLE.COM

Testsciipl | Output] Statisltcs} PiofSet]


!

E> "u 6*"ul '-%, &


v_Hax Student s
v_ReturnVa.iue
v FullPaircftnt
BEGIN

| li-O Gtarted tc
MDSYS.SOO.
MDSYS.SDO.
MDSYS.SDO.
i MDSYS.SDO,
MDSYS.SDO. ^

Documents Wtidow

'

NU1IBEB ;
BOOLEW.';
CONSTANT K1IUBER := 80;

J;

SELECT current- students , X_ students


INTO v_CurrentStud*nt*, v_Hax Students
classes
department - p_Department
) course p Course;

Templates
Package etementtd
-DPLSQLT,pes
3 Q Program units
J
j
L
< Function
1
i Java source
: Packaoe
J

.
^\Script^a!mOtfujly'

Program Window - Edit sot]

p_Course

IT tv Cur rent Students / v HmxStudent

Variable
v_CufientStudenfs

iOC> >- v_FullPeccent THEN


^,

Jy^8
4

!
-

Call stack
ALMOST"nJll[Line221

v_RetumValue:-~TRUET

410

S SQL Window" BEGIN DE


Test Window Script for fu

IP

feeoiing...

. 2.35.

. PL/SQL,
SQL. , .
. PL/SQL Developer . web-
Allround Automations, .
PL/SQL.
.
Profiler
.
.
,
.
PL/SQL. PL/SQL .
,
Oracle.

63



2.2
PL/SQL. , , .

.
2.2.
PL/SQL
SQL
Navigator

TOAD

SQLPL/SQL
Programmer Developer

Her

Hei


Java OracleSi

Her

Her

PL/SQL

Java

PL/SQL

SQL,
PL/SQL

SQL, PL/SQL, SQL, PL/SQL, SQL, PL/SQL,


HTML
Java, HTML Java

SQL'Plus

Rapid SQL

DBPartner

SQL, PL/SQL

SQL, PL/SQL SQL, PL/SQL,


Java

64

,
PL/SQL, .
PL/SQL,
PL/SQL. 3 PL/SQL.


PL/SQL

3
PL/SQL

68

,
PL/SQL. , PL/SQL.
PL/SQL, , ,
. ,
PL/SQL ,
.
PL/SQL , SQL-. ( : (operator) ,

, SQL- (statement)
( ),
PL/SQL. , .)
, . SQL-
. 7
PL/SQL, 4, 5 6 SQL-.

PL/SQL
, PL/SQL,
. PL/SQL,
() .
: . . , ,
, . , .
:
(labeled block) , .
.
, , , .
(subprogram) . , .
.
.
, , .

PL/SQL

69

(triggers) ,
, . , ,
. , , (DML, data manipulation language) .
DML INSERT (), UPDATE ()
' DELETE (). (DDL, data definition language), CREATE
DROP, , .
PL/SQL,
temp_table , . SQL*Plus:
;_J -- AnonymousBlock.sql
SQL> DECLARE
2 /* , . */
3
v_Num1
NUMBER := 1;
4 v_Num2
NUMBER := 2;
5
v_String1
VARCHAR2(50) := 'Hello World!';
6
v_String2
VARCHAR2(50) :=
7
- This message brought to you by PL/SQL!';
8
v_OutputStr VARCHAR2(50);
9 BEGIN
10 /* ,
11
temp_table. */
12 INSERT INTO tempjtable (num_col, char_col)
13
VALUES (v_Num1, v_String1);
14 INSERT INTO tempjtable (num_col, char_col)
15
VALUES (v_Num2, v_String2);
16
17 /* temp_table
18
DBMS_OUTPUT . */
19 SELECT char_col
20
INTO vJMputStr
21
FROM tempjtable
22
WHERE num_col = v_Num1;
23
OBMS_OUTPUT.PUT_LINE(v_OutputStr);
24
25
SELECT char_col
26
INTO v_OutputStr
27
FROM temp_table
28
WHERE num_col = v_Num2;
29
DBMSJ)UTPUT.PUT_LINE(v_OutputStr);
30
31 /* */
32 ROLLBACK;
33 END;

70

3
34/
Hello World!
- This message brought to you by PL/SQL!
PL/SQL procedure successfully completed.

,
,
, temp_table.
tables, sql.
,
README. DBMS_OUTPUT
2.
, DECIv\RE
, .
END.
Q - LabeledBlock.sql
SQL> !_InsertIntoTemp
2 DECLARE
3
/* , . */
4
v_Num1
NUMBER := 1;
5
v_Num2
NUMBER := 2;
6
v_String1
VARCHAR2(50) := 'Hello World!';

7 v_String2 VARCHAR2(50) := '- This message brought to you


8
by PL/SQL!';
9
v_OutputStr VARCHAR2(50);
10 BEGIN
11 /* ,
12
temp_table. */
13 INSERT INTO temp_table (num_col, char_col)
14VALUES (v_Num1, v_String1);
15 INSERT INTO tempjtable (num_col, char_col)
16
VALUES (v_Num2, v_String2);
17
18 /* temp_table
19
DBMS_OUTPUT . */
20
SELECT char_col
21
INTO v_OutputStr
22
FROM temp_table
23
24

WHERE num_col = v_Num1;


DBMSJXJTPUT. PUT_LINE(v_OutputStr);

25
26
28
29
30

SELECT char._col
INTO v_OutputStr
FROM temp_table
WHERE num_col = v_Num2;
DBMS_OUTPUT.PUT_LINE(v_OutputStr);

PL/SQL

71

31

32 /* */
33 ROLLBACK;
34
35 END l_InsertIntoTemp;
36 /
Hello World!
- This message brought to you by PL/SQL!
PL/SQL procedure successfully completed.
,
DECLARE CREATE OR REPLACE
PROCEDURE (. 9 10). ,
END.
)

-- Procedure.sql
CREATE OR REPLACE PROCEDURE InsertlntoTemp AS
/* , . */
v_Num1
NUMBER := 1;
v_Num2
NUMBER := 2;
v_String1
VARCHAR2(50) := 'Hello World! - ;
v_String2
VARCHAR2(50) :=
'-- This message brought to you by PL/SQL!';
v_OutputStr VARCHAR2(50);
BEGIN
/* ,
temp_table. */
INSERT INTO temp_table (num_col, char_col)
VALUES (v_Num1, v_String1);
INSERT INTO temp_table (num_col, char_col)
VALUES (v_Num2, v_String2);
/* temp_table
DBMS_OUTPUT . */
SELECT char_col
INTO v_OutputStr
FROM temp_table
WHERE num_col = v_Num1;
DBMS_OUTPUT.PUT_LINE(v_OutputStr);
SELECT char_col
INTO v_OutputStr
FROM temp_table
WHERE num_col = v_Num2;
DBMS_OUTPUT.PUT_LINE(v_OutputStr);
/* */
ROLLBACK;
END InsertlntoTemp;

72

:
I
FJ -- Procedure.sql
SQL> BEGIN
2 InsertlntoTemp;
3 END;
4/
Hello World!
- This message brought to you by PL/SQL!
PL/SQL procedure successfully completed.

9 10.
temp_table , num_col . ( 11.)
, temp_table .
) - trigger.sql
CREATE OR REPLACE TRIGGER OnlyPositive
BEFORE INSERT OR UPDATE OF num_col
ON temp_table
FOR EACH ROW
BEGIN
IF :new.num_col < 0 THEN
RAISE_APPLICATION_ERROR(-20100. 'Please insert a positive v a l u e ' ) ;
END IF;
END OnlyPositive;

, INSERT
UPDATE temp_table. SQL*Plus :
] - trigger.sql
SQL> -- INSERT ,
SQL> INSERT INTO tempjtable (num_col, char_col)
2
VALUE(1, 'This is row );
1 row created
SQL> - INSERT ,
SQL> INSERT INTO temp_table (num_col, char_col)
2
VALUES (-1, 'This is row -);
INSERT INTO temp_table(num_col, char_col)
ERROR at line 1;
ORA-20100: Please insert a positive value
ORA-06512: at "DEMO.ONLYPOSITIVE", line 3
ORA-04088: error during execution of trigger 'DEMO.ONLYPOSITIVE'

PL/SQL

73


: ,
.
; . ,
, :
f_j -- allthree.sql
DECLARE

/* */
v_StudentID NUMBER(5) := 10000;
v_FirstName VARCHAR2(20);

-
- 10000.
-
- 20.

BEGIN
/* */
-- , 10000.
SELECT first_name
INTO v_FirstName
FROM students
WHERE id = v_StudentID;
EXCEPTION
/* */
WHEN NO_DATA_FOUND THEN
- .
INSERT INTO log_table (info)
VALUES ('Student 10,000 does not exist!');

END;

,
tables, sql: students
log_table. , ,
, 1.

, , .
.
. . ,
SQL-.
. ; ,
.
4 6. , 7.
DECLARE (), BEGIN (), EXCEPTION ( ) END
(). , ,
. ,
:

74

DECLARE
/* */
BEGIN
/* */
EXCEPTION
/* */

END;

DECLARE
. ,
. DECLARE
(. 9 11).
,
BEGIN. , EXCEPTION
END . ,
, , :
BEGIN

/* */

END;

,
:
DECLARE

/* */
BEGIN
/* */

END;
|

/"
,,* /* */,
(. ).


, :
Q - nested.sql
DECLARE
/* */
v_StudentID NUMBER(5) := 10000; --
- 10000
v_FirstName VARCHAR2(20);
-
-- 20
BEGIN
/* */

PL/SQL

75

- , 10000
SELECT first_name
INTO v_FirstName
FROM students
WHERE id = v_StudentID;
- ,
BEGIN
INSERT INTO log_table(info)
VALUECHello from a nested block! ');
END;
EXCEPTION
/* */
WHEN NO DATA_FOUND THEN
- ,
-
BEGIN
-
INSERT INTO log_table(info)
VALUESCStudent 10,000 does not exist! ');
EXCEPTION
WHEN OTHERS THEN

- - INSERT
DBMS_OUTPUT.PUT_LINECError inserting into log_table! ');

END;
END;


PL/SQL . , , , PL/SQL.
:
: Z z
: 0-9
: ,
: + - * / < > =
: () {} [] ? ! - ; : . "' @ # % $ & _ |
PL/SQL , . SQL, PL/SQL . , .
,
.
, , .

76

PL/SQL,
, , . ,
, , , , #. . 30 , .
:

Q *

v_StudentID
TempVar
v1
v2_
social_security_#.

:
G

_temp_

First Name
This_is_a_really_long_identifier
1_variable

'~ +
-
- ,
-
- 30
-
-

PL/SQL , PL/SQL :
)

Room_Description
room_description
ROOM_DESCRIPTION
rOOm_DEscriPTIOn


(. ).


, ( ) , PL/SQL .
. , BEGIN END
PL/SQL, .
, begin . :
)

DECLARE
begin NUMBER;

PL/SQL

77

,
. ,
:
Q

DECLARE
v_BeginDate DATE;

,
. .

, , , ,
.
:
(_] "A number"
"Linda's variable"
"/"
"X/Y"

30 ( ).
, .
PL/SQL SQL-. PL/SQL , SQL (. ). ,
, exception ( ), :
)

DECLARE
v_Exception
VARCHAR2(10);
BEGIN
SELECT "EXCEPTION"
INTO v_Exception
FROM exception_table;
END;

, "EXCEPTION"
. Oracle , (
CREATE)
. , "EXCEPTION" .

, .

78

, PL/SQL
. PL/SQL
, SQL, , PL/SQL,
SQL.
exception_table .

except!on_table
PL/SQL,
. ,
,
.
PL/SOL.
, exception_table
:
CREATE TABLE exceptionable (
exception
VARCHAR2(20),
date_occured DATE);
:
CREATE VIEW exception_view AS
SELECT exception exception_description,
date_occured
FROM exception_table;
exception..table
exception_view,
exception_description,
.

( ),
PL/SQL.
.
PL/SQL 3.1.
3.1. PL/SQL

""


""

""

79

PL/SQL

3.1. PL/SQL ()

"

**

" "

!=

" "
( <>)
" "
( "=)

" "
( !=)
<=

"
"

>=

"
"

:=

=>

11


()

/*

*/

<space>

<tab>

<>

, ,
, -23.456 NULL. ,
"
PL/SQL".

( ) , . (
, SQL.) , CHAR VARCHAR2, . , :
'12345'

'Four score and seven years ago. . . '


'100%'
, CHAR. PL/SQL,
. !
,

80

. , "Mike's string" :
'Mike''s string'

, PL/SQL ,
, :
,
,
. ,
. PL/SQL NULL-.

, . ,
'12345' , '01-JAN-2001'
(. ).

,
. , NUMBER. , .
, +
-. .
:
Q 123
_j
+12

(
), + -. :

-17.1
23.0
3.

23.0 3. ,
PL/SQL . . :
]

1.3457
9.87-3
-7.12+12

PL/SQL

81

. "", .. " 10 ...". ,


:
1.3457 = 1.345 10 7
= 1.345 10 000 000 = 13 450 000
9.87-3 = 9,87 10 -3 = 9.87 .001 = 0.00987
-7.12+12 = -7.12 10 12
= -7.12 1 000 000 000 000 = -7 120 000 000 000

6 NLS

(, ).

Oracle NLS. NLS Oracle9\
.


: TRUE (), FALSE
() NULL. () .
IF LOOP.

. PL/SQL .
: . -.

( ).
PL/SQL:
;

- comments.sql
DECLARE
v_Department
CHAR(3);
v_Course
NUMBER;
BEGIN
INSERT INTO classes (department, course)
VALUES (v_Department, v_Course);
END;

, :
Q comments.sql
DECLARE

82
v
v_Department CHAR(3); --
-
v_Course NUMBER;
-
BEGIN
- classes ,
- v_Department v_Course.
INSERT INTO classes (department, course)
VALUES (v_Department, v_Course);
END;

,
()
.


/* */, .
:
| comments.sql
DECLARE
v_Department
CHAR(3);
/*
*/
v_Course
NUMBER;
/* */
BEGIN
/* classes ,
v_Department v_Course. */
INSERT INTO classes (department, course)
VALUES (v_Department, v_Course);
END;

, , ..
. :
) -- comments.sql

BEGIN

/* .
/* */, . */
NULL;
END;

,
/*.
*/, .

PL/SQL

83


PL/SQL . * (variables) ,
. .
, ,
.
PL/SQL.
. , .


. :
_ [CONSTANT] [NOT NULL] [:= };
_ , , .
:
Q

DECLARE
v_Description VARCHAR2(50);
v_NuinberSeats NUMBER := 45;
v_Counter
BINARY_INTEGER := 0;

PL/SQL. VARCHAR2, NUMBER BINARY_INTEGER PL/SQL. v_NumberSeats


v_Counter 45 0. , v_0escription, (
), NULL. NOT NULL, .
, , NOT NULL,
NULL , . , ,
, v_TempVar NOT NULL,
:
Q

DECLARE
vJempVar NUMBER NOT NULL;

, v_TempVar , :
)

DECLARE
vJempVar NUMBER NOT NULL := 0;

CONSTANT,

84

.
" ". , ,
:
_)

DECLARE
cJunimumStudentlD CONSTANT NUMBER(5) := 10000;

v
Q

:=
DEFAULT ( ). :
DECLARE
v_NumberSeats
NUMBER DEFAULT 45;
v_Counter
BINARY_INTEGER DEFAULT 0;
v_FirstName
VARCHAR2(20) DEFAULT 'Scott 1 ;


. ,
:
)

DECLARE
v_FirstName, v_LastName VARCHAR2(20);

:
] DECLARE
v_FirstName VARCHAR2(20);
v_LastName
VARCHAR2(20);


, . .
;
, .
PL/SQL , , NULL.
NULL " ", , NULL . PL/SQL.
( Ada) . (, Java) .

PL/SQL
Oracle? PL/SQL : ,
. OracleS LOB
. , .

85

PL/SQL


: :
BINARY INTEGER
CHAR
DEC
CHARCTER
DECIMAL
LONG
1
DOUBLE PRECISION
NCHAR
1
FLOAT
NVARCHAR2
INT
STRING
INTEGER
VARCHAR
NATURAL
VARCHAR2
NATURALN
NUMBER
Rowid:
ROWID
NUMERIC
2
UROWID
PLS INTEGER
POSITIVE
POSITIVEN
Trusted:
REAL
MLSLABEL
SIGNTYPE
SMALLJNT


RECORD
NESTED TABLE1
INDEX-BY TABLE
VARRAY1
1
2
3

LOB
BFILE1
LOB1
CLOB1
NLOB1

:
DATE
3
INTERVAL DAY TO SECOND
3
INTERVAL YEAR TO MONTH
3
TIMESTAMP
3
TIMESTAMP WITH TIME ZONE
3
TIMESTAMP WITH LOCAL TIME ZONE

:
BOOLEAN
Raw:
RAW
LONG RAW


REF CURSOR
REF1


3
SYS.ANYTYPE3
SYS.ANYDATA3
SYS.ANYDATASET3

OracleS
OracleSi
Oracle9i

. 3.1. PL/SQL

. . 3.1
PL/SQL.
PL/SQL STANDARD. PL/SQL. , STANDARD SQL-
, PL/SQL.


, ,
,
. : , , RAW, ,
ROWID, Trusted.


. : NUMBER, PLS_INTEGER
BINARY_INTEGER. , NUMBER,

86

, ,
BINARYJNTEGER PLSJNTEGER - .
NUMBER , ,
. NUMBER, . :
NUMBER (P,S);
(precision), a 5 (scale). ,
. , , .
3.2.
3.2.

NUMBER

1234.5678

1234.5678

NUMBER(3)

123

123

NUMBER(3)

1234

NUMBER(4,3)

123.4567

NUMBER(4,3)

1.234567

1.235'

NUMBER(7,2)

12345.67

12345.67

NUMBER(3, -3)

1234

10002

NUMBER(3, -1)

1234

12302

' , ,
.
2

, , ,
.

38 ,
-84 127.
(subtype) .
,
(. ). NUMBER
, , , ,
NUMBER, .

, . NUMBER :

DEC
DECIMAL
DOUBLE PRECISION
FLOAT

PL/SQL

87

NUMERIC
REAL
, ,
DEC, DECIMAL NUMERIC 38 . DOUBLE PRECISION FLOAT 126 , 38 .
REAL 63 , 18 .
, INTEGER, INT SMALINT 38 .
BINARY_INTEGER , NUMBER, ,
. NUMBER.
, NUMBER
. , NUMBER,
PL/SQL , ( ) NUMBER .
, ,
BINARYJNTEGER. , -2 147 483 647 +2 147 483 647.
, ,
. BINARYJNTEGER .
NUMBER, BINARYJNTEGER . NUMBER BINARYJNTEGER , ..
. BINARYJNTEGER 3.3.
3.3. BINARYJNTEGER

NATURAL
NATURALN
POSITIVE
POSITIVEN
SIGNTYPE

0...2 147 483 647


0...2 147 483 647 NOT NULL
1...2 147 483 647
1...2 147 473 647 NOT NULL
-1,0,1

PLS_INTEGER PLSJNTEGER ,
BINARYJNTEGER -. -2 147 483 647 +2 147 483 647, . ,
PLSJNTEGER, .

88

, BINARY_INTEGER, NUMBER ( )
. SQL*Plus (. "
"):
| -- integers, sql
SQL> DECLARE
2
v_Bin!nt BINARY_INTEGER;
3 BEGIN
4
- v_Bin!nt
5
vBinlnt := 2147483647;
6
/'
-- 1 v_Bin!nt ( ),
8 -- .
9
- BINARY_INTEGER,
10 -- .
11 v_Bin!nt := v_Bin!nt + 1 - 1 ;
12 END;
13 /
PL/SQL procedure successfully completed.
SQL DECLARE
2
v_PLSInt PLS_INTEGER;
3 BEGIN
4
- v_PLSInt
5 v_PLSInt := 2147483647;
6
7
- 1 v_PLSInt ( ),
8
- .
9
- PLS_INTEGER,
10
, ORA-1426.
11 v_PLSInt := v_PLSInt + 1 - 1 ;
12 END;
13 /
DECLARE
ERROR at line 1:
ORA-01416: numeric overflow
ORA-06512: at line 11

. VARCHAR2, CHAR
LONG, NCHAR NVARCHAR2 ( OracleS ).
VARCHAR2 VARCHAR2, . VARCHAR2
. , VARCHAR2, :

PL/SQL

89

VARCHAR2(L)
L (length) . . VARCHAR2 32 767 . ,
, VARCHAR2, 4000 . PL/SQL- VARCHAR2
4000 , , LONG, 2
GLOB (4 ). , LONG CLOB
VARCHAR2, 32 767 .

Oracle? ,
VARCHAR2, 2000 . ,
PL/SQL- VARCHAR2
Oracle? VARCHAR2,
2000 .

VARCHAR2 , .
, ASCII, EBCDIC Code Page 500 , Unicode.
,
,
VARCHAR2, , .
, .
VARCHAR STRING VARCHAR2.

: VARCHAR VARCHAR2?
VARCHAR ANSI, VARCHAR2 Oracle.
. ANSI
VARCHAR , Oracle VARCHAR2
,

19 VARCHAR2
VARCHAR2(L[CHAR|BYTE])
L . CHAR
BYTE , L
( CHAR). , , - 32 767 . ,
UTF8, .
UTF8 3 . , ,
VARCHAR2(300 BYTE), 100 .

90

CHAR
. CHAR :
CHAR[(L)]
L . VARCHAR2
. , , 1, . CHAR ,
.
, CHAR
(. 4).
CHAR 32 767 . , CHAR,
2000 . , CHAR 2000 ,
VARCHAR2 ( <= 4000 ) LONG. , LONG CHAR , 32 767 .

Oracle? , CHAR,
255 .

VARCHAR2, CHAR
, . , , VARCHAR2, ,
.
CHAR, , CHARACTER.
VARCHAR2 CHAR
(. 4).
19 CHAR
CHAR[(L[CHAR|BYTE])]
L . CHAR BYTE
, L
( CHAR). , , - 32 767 . ,
UTF8,
. UTF8 3 . , ,
CHAR(300 BYTE), 100 ( )
.

PL/SQL

91

LONG LONG, 2 , LONG


PL/SQL
, 32 760 .
LONG VARCHAR2.
LONG 32 760 , PL/SQL- LONG . PL/SQL- LONG , LONG
, PL/SQL- LONG
LONG .
NCHAR NVARCHAR2 OracleS
. NLS (National Language Support
): NCHAR NVARCHAR2.
, , PL/SQL.
(national character set).
NCHAR NVARCHAR2 , CHAR VARCHAR2.

. , . , .

/9/ NCHAR NVARCHAR2


.

NCHAR, NVARCHAR2 NLS "Server SQL Reference".

RAW
. Oracle ,
. , ,
. , (raw
type), .
RAW RAW CHAR, .
RAW :
RAW(L) ,
L . RAW
. , RAW
.

92

3
RAW 32 767 .
RAW 2000 (255 Oracle?), ,
2000 , RAW .
, LONG RAW, 2 . , LONG RAW 32 767 , PL/SOJL- RAW.
LONG RAW LONG RAW LONG
, PL/SQL
.
LONG RAW 32 760 . LONG RAW
2 , , 32 760 , PL/SQL- LONG
RAW . PL/SQL- LONG RAW
LONG RAW ,
PL/SQL- LONG RAW LONG
RAW .

(/)
: DATE, TIMESTAMP
INTERVAL. TIMESTAMP INTERVAL OracleQ .
DATE PL/SQL DATE DATE, . DATE
, , , , , ,
. . DATE 7 ,
( ).
DATE DATE.

. TO_DATE
TO_CHAR . " "
5.
TIMESTAMP TIMESTAMP DATE ,
, , , ,
. . TIMESTAMP :
TIMESTAMP [(P)]
, 6.
TIMESTAMP WITH TIME ZONE
.
:

PL/SQL

93

TIMESTAMP [(P)] WITH TIME ZONE


.
TIMESTAMP WITH LOCAL TIME ZONE
, .
:
TIMESTAMP [()] WITH LOCAL TIME ZONE
.
INTERVAL INTERVAL
. INTERVAL YEAR TO MONTH
INTERVAL YEAR[(P)] TO MONTH
, 2.
INTERVAL DAY TO SECOND
INTERVAL DAY[(Z>P)] TO SECOND[(SP)]
DP ( 2), a SP
( 6).

ROWID
: ROWTD UROWID. UROWID
18 .
ROWID PL/SQL ROWID ,
ROWID .
(rowid),
, . ,
.
ROWTDTOCHAR. 18- , Oracle?
:
)

BBBBBBBB.RRRR.FFFF

, RRRR
, a FFFF .
. ,
Q

0000001E.OOFF.0001

30- , 255- ,
1. OracleS rowid
, 18-
, base-64.

94

rowid
DBMS_ROWID, .
PL/SQL;
ROWID . WHERE UPDATE DELETE.
UROWID , Oracle, , . ,
- rowid,
. ,
Oracle, ,
rowid. UROWID rowid
(.. ROWID), rowid. Oracle UROWID , .
rowid - "Oracle Concepts".

BOOLEAN.

PL/SQL, IF-THEN-ELSE LOOP. BOOLEAN: TRUE, FALSE NULL.
, 0
BOOLEAN:
DECLARE
v_ContinueFlag BOOLEAN := 0;

Trusted
MLSLABEL,
Trusted Oracle . Oracle , MLSLABEL, NULL-.
MLSLABEL 2 5
, , .
MLSLABEL
255 .

MLSLABEL Orac/eSi.


PL/SQL : , ( ) .
. , ,
( ).

PL/SQL

95

" PL/SQL", a
8.


PL/SQL , .
.

, (. ). .
PL/SQL , . , ,
.
Oracle 7 REF CURSOR, (. 4). OracleS
REF, .

LOB
LOB . (large object) , 4 .
, , LONG LONG RAW,
. LOB DBMSJLOB
(. 12).


,
( ) (). OracleS
. OracleQz ,
(. 12).

%TYPE
,
, PL/SQL. , , , . , first_name students
VARCHAR2(20). :
)

DECLARE
v_FirstName VARCHAR2(20);

96

, , first_name . , first_name
VARCHAR2(25). PL/SQL,
, :
Q

DECLARE
v_FirstName VARCHAR2(25);

PL/SQL ,
, , , . %TYPE.
. :
| DECLARE

v_FirstName students.first_name%TYPE;

%TYPE v'_FirstName
, first_name students. , (,
..). %TYPE
PL/SQL, .
%TYPE:
]

DECLARE
v_RoomID
v_RoomID2
v_TempVar
v_AnotherVar

classes.room_id%TYPE; -- NUMBER (5)


v_RoomID%TYPE;
- NUMBER (5)
NUMBER(7,3) NOT NULL := 12.3;
v_TempVar%TYPE;
- NUMBER (7,3)

%TYPE (),
() NOT NULL (, classes. room_id
v_TempVar), . , v_RoomID, v_RoomID2
v_AnotherVar . ,
NULL-.
%TYPE , PL/SQL ,
.

,
(subtype) PL/SQL, . , . PL/SQL
(, DECIMAL INTEGER - NUMBER) STANDARD.
:
SUBTYPE _ IS _;

97

PL/SQL

_ , _
. , , %TYPE. :
j_)

DECLARE

SUBTYPE t_LoopCounter IS NUMBER;


-
v_l_oopCounter t_LoopCounter;
-
SUBTYPE t_NameType IS students. first_name%TYPE;

SUBTYPE.
:
U

DECLARE
SUBTYPE T_LoopCounter IS NUMBER (4);

--

: ( ) SUBTYPE %TYPE:
Q

DECLARE
v_DummyVar NUMBER (4);

- ,
--
SUBTYPE t_LoopCounter is v_DummyVar%TYPE;
- NUMBER(4)
v_Counter t_LoopCounter;

OracleSz. :
]

DECLARE

SUBTYPE t_LoopCounter IS NUMBER(4); .- OracleSi


:
Q

DECLARE
SUBTYPE t_Nutneric IS NUMBER; -- ,
v_Counter is t_Numeric (5);
-

, .


PL/SQL . , ,
. , CHAR(IO) VARCHAR2(1),
. , ,
NUMBER(3,2) NUMBER(3) . PL/SQL ,

.

98

:
.


, SQL,
PL/SQL. 3.4.

, .

5.
3.4. PL/SQL SQL

TO_CHAR

VARCHAR2

( )
TO_DATE
DATE

( )
TOJIMESTAMP"
TIMESTAMP

( )
TOJIMESTAMPJZ* TIMESTAMP
WITH TIMEZONE
( )
TO_DSINTERVAL*
INTERVAL DAY
SECOND
( )
TO_YMINTERVAL*
INTERVAL YEAR
MONTH
( )
TO_NUMBER
NUMBER

( )
RAWTOHEX
RAW


HEXTORAW

CHARTOROWID

ROWID

ROWIDTOCHAR


ROWID 18-

OracleSi .

,

,






RAW
(

)
(

18-
)
ROWID

PL/SQL

99


PL/SQL
, . , ,
, 10002:
_|

DECLARE

v_CurrentCredits VARCHAR2(5);
BEGIN
SELECT current_credits
INTO v_Currenteredits
FROM students
WHERE id = 10002;
END;

c u r r e n t _ c r e d i t s NUMBER(3), v_CurrentCredits VARCHAR2(5). PL/SQL ,


. PL/SQL
:


PL/SQL ,
.
TO_CHAR:
[_) DECLARE
v_CurrentCredits VARCHAR2(5);
BEGIN
SELECT TO_CHAR (current_credits)
INTO v_CurrentCredits
FROM students
WHERE id = 10002;
END;

,

TO_CHAR. .

PL/SQL (. " "). : .


(scope) , .
PL/SQL .

100

, PL/SQL
, , . . 3.2 , v_Character ;
END . v_Number END
. .
fDECLARE
v Number NUMBER(3,2);
BEGIN
v_Number2 ^

DECLARE
v Character VARCHAR2( 10);
BEGIN

v_Character

END;

. 3.2.
(visibility) ,
. ; ,
. . 3.3. 1 v_AvailableFlag
v_SSN . 2
, v_AvailableFlag.
DECLARE
v AvailableFlag BOOLEAN;
v_SSN
NUMBER(9);
BEGIN
DECLARE
v_SSN
CHAR(11);
v_StartDate DATE;
BEGIN

END;

v_AvailableFlag
v_SSN NUMBER(9)

v_AvailableFlag,
v_StartDate v_SSN CHAR(11)

v_AvailableFlag
v_SSN NUMBER(9)

. 3.3.

101

PL/SQL

v_SSN CHAR(ll) NUMBER(9) .



, : v_AvailableFlag, v_StartDate v_SSN
CHAR(ll). 3 v_StartOate v_SSN CHAR(ll)
.
, 1: v_AvailableFlag
v_SSN NUMBER(9).
,
, ? . 3.4.
, . 3.3,
l_0uter (. "
PL/SQL"). 2 v_SSN NUMBER(9) .
:
l_Outer.v_SSN
1 Outer
DECLARE
v AvailableFlag
v SSN
BEGIN

BOOLEAN;
NUMBER(9);

v AvailableFlag
v SSN NUMBER(9)

4"

DECLARE
v SSN
v StartDate
BEGIN

CHAR(H)'
DATE;

v_AvailableFlag, v_Stari:Date
v_SSN CHAR(11),
1 Outer.v SSN
v_SSN NUMBER(9)

END;

'

*-__

END;

^^~____

-_ v AvailableFlag
v_SSN NUMBER(9)
. 3.4.


PL/SQL.
. (expression)
, , (operator). , ,
.

102

(assignment).
:
:= ;
PL/SQL,
PL/SQL.
. :
Q

DECLARE
v_String1
VARCHAR2(10);
v_String2
VARCHAR2(15);
v_Numeric NUMBER;
BEGIN
v_String1 := 'Hello';
v_Strlng2 := v_String1;
v_Numeric := -12.4;
END;

, , (lvalue), ,
, (rvalue). , . , ,
. PL/SQL , 'Hello' -12. 4
. , , .
: 'Hello' , a v_String~l . , .
, .
, ,
(statement) PL/SQL . , :
Q

DECLARE

v_Va11 NUMBER;
v_Va12 NUMBER;
v_Va13 NUMBER;
BEGIN
v_Va11 := v_Va12 := v_Va13 := 0;

END;

PL/SQL (rvalues),

103

PL/SQL

. ,
SQL-. .
. PL/SQL
(, , ), (, , ). , (-) , (*) .
.
:

3 + 5*7

, 38 (3+35), 56 (8*7).
, , . , 56:
(3 + 5) * 7

3.5. PL/SQL

", NOT

*,/

,
,

, ,

=, !=, <, >, <=, >=, IS NULL,


LIKE, BETWEEN, IN

(
IS NULL,
)

AND

OR


,
(| |).
( , ). ,
'Hello' || 'World' || ' i '

_| 'Hello World ! '

104

CHAR,
CHAR.
VARCHAR2, VARCHAR2. ,
CHAR, CHAR. v_Result , VARCHAR2:
]

DECLARE

VARCHAR2(10) := 'PL';
VARCHAR2(20);
v_Result
BEGIN
'/SQL';
v_Result := v_TempVar
v_TempVar

END;


PL/SQL ( GOTO) , . ,
, ,
(TRUE (), FALSE () NULL).
:
X > Y
NULL

(4 > 5) OR (-1 != Z)

AND (), OR () NOT () .


(. . 3.5). . AND TRUE , , OR FALSE ,
.
NOT

TRUE FALSE NULL


FALSE TRUE NULL

TRUE FALSE NULL


TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL

AND

OR
TRUE FALSE NULL
TRUE TRUE TRUE TRUE
FALSE TRUE FALSE NULL
NULL TRUE NULL NULL

. .5.

PL/SQL

105

NULL- (,
NULL ).

Q TRUE AND NULL

NULL, , .
"NULL-".
, , , , .
, .

<
>

()
()

>=

IS NULL TRUE ,
NULL. NULL-
,
, NULL, NULL.
LIKE () , , Unix. (_)
, (%) . TRUE:
Q

'Scott' LIKE 'Sc%t'


'Scott' LIKE 'Scjit'
'Scott' LIKE '%'

BETWEEN () <= >=


. , FALSE:
Q

100 BETWEEN 110 AND 120

TRUE:
)

100 BETWEEN 90 AND 110

IN () TRUE,
, . ,
FALSE:
[_] 'Scott' IN ('Mike', 'Pamela', 'Fred')

106

NULL-, ,
NULL
NULL.

PL/SQL
PL/SQL, ,
, .
.

PL/SQL.

IF-THEN-ELSE
IF-THEN-ELSE (--):
IF _! THEN
_1;
[ELSIF _2 THEN
_2; ]
[ELSE
_; ]
END IF;
_ , (. ). ELSIF ELSE , ELSIF . ,
, IFTHEN-ELSE ELSIF ELSE:

FJ if 1. sql
DECLARE

v_NumberSeats rooms.number_seats%TYPE;
v_Comment VARCHAR2(35);
BEGIN
/* , 20008.
v_NumberSeats. */
SELECT number_seats
INTO v_NumberSeats
FROM rooms
WHERE room_id = 20008;
IF v_NumberSeats < 50 THEN
v_Comment := 'Fairly small';
ELSIF v_NumberSeats < 100 THEN
v_Comment := 'A little bigger';
ELSE
v_Comment := 'Lots of room';
END IF;
END;

PL/SQL

107

,
. , .
Q v_NumberSeats < 50


FJ v_Comment := 'Fairly small';
50, :
) v_NumberSeats < 100
, :
) v_Comment := 'A little bigger';
, 100,
:
_} v_Comment := 'Lots of room';


.
. ( SQL-).
:
Q if2.sql
DECLARE
v_NumberSeats rooms.number_seats%TYPE;
v_Comment VARCHAR2(35);
BEGIN
/* , 20008.
v_NumberSeats. */
SELECT number_seats
INTO v_NumberSeats
FROM rooms
WHERE room_id = 20008;
IF v_NumberSeats < 50 THEN
v_Comment := 'Fairly small';
INSERT INTO temp_table (char_.col)
VALUES ('Nice and cozy');
ELSIF v_NumberSeats < 100 THEN
v_Comment := ' A little bigger';
INSERT INTO temp_table (char_col)
VALUES ('Some breathing room');
ELSE
v_Comment := 'Lots of room';
END IF;
END;

108

I
| ELSIF
.
Ada.
NULL
IF-THEN-ELSE
.
FALSE NULL,
. :
Q

/* 1 */
DECLARE
v_Number1
v_Number2
v_Result
BEGIN

NUMBER;
NUMBER;
VARCHAR2(7);

IF v_Number1 < v_Number2 THEN

v_Result := 'Yes';
ELSE
v_Result := 'No';
END IF;
END;
/* 2 */
DECLARE
v_Number1 NUMBER;
v_Number2 NUMBER;
v_Result VARCHAR2(7);
BEGIN
IF v_Number1 >= v_Number2 THEN
v_Result := 'No';
ELSE
v_Result ;= 'Yes';
END IF;
END;
? ,
v_Number1 = 3, a v_Number2 = 7. 1 (3 < 7) , v_Result 'Yes'. 2
(3 >= 7), v_Result
'Yes'. v_Number1 v_Number2, NULL,
.
, v_Number1 = 3, a v_Number2 NULL.
? 1 (3 < NULL) NULL, ELSE v_Result 'No'. 2 (3 >= NULL )
NULL, ELSE

PL/SQL

109

v_Result 'Yes'. (v_Number~l v_Number2) NULL, -.


, .
NULL:
/* 1 */
DECLARE
v_Number1
NUMBER;
v_Number2
NUMBER;
v_Result
VARCHAR2(7);
BEGIN
IF v_Number1 IS NULL OR
v_Number2 IS NULL THEN
v_Result := 'Unknown 1
ELSIF v_Number1 < v_Number2 THEN
v_Result := ' Y e s ' ;
ELSE
v_Result := ' N o ' ;
END IF;

END;
/* 2 */
DECLARE
v_Number1 NUMBER;
v_Number2 NUMBER;
vjtesult VARCHAR2(7);
BEGIN
IF v_Number"l IS NULL OR
v_Number2 IS NULL THEN
v_Result := 'Unknown'
ELSIF v_Number1 >= v_Number2 THEN
v_Result := ' N o ' ;
ELSE
v_Result := ' Y e s ' ;
END IF;
END;

IS NULL ,
NULL-. . NULL v_Result
'Unknown' (),
v_Number NULL- . v_Number1
v_Number2 , ,
NULL- ;
.

110

CASE
IF-THEN-ELSE
.
, ,
:
)

case.sql
DECLARE
v_Major students.major%TYPE;

v_CourseName VARCHAR2(10);
BEGIN
-
SELECT major
INTO v_Major
FROM students
WHERE ID = 10011;
-
IF v_Major = 'Computer Science' THEN
v_CourseName = 'CS 101';
ELSIF v_Major = 'Economies' THEN
v_CourseName = 'ECN 203';
ELSIF v_Major = 'History' THEN
v_CourseName = 'HIS 101';
ELSIF v_Major= 'Music' THEN
v_CourseName = 'MUS 100';
ELSIF v_Major = 'Nutrition' THEN
v_CourseName = 'NUT 307';
ELSE
v_CourseName = 'Unknown';
END IF;
DBMS_OUTPUT.PUT_LINE(v_CourseName);

END;

v_Major
ELSIF. OracleQ , . CASE. , CASE :
CASE test_var
WHEN _1 THEN __1;
WHEN _2 THEN __2;
WHEN _ THEN __;
[ELSE _1$;]
END CASE;
test_var , _1... _ , __1 ... __ .

PL/SQL

111

test_var , , _2, __2. ,


_.
CASE:
- case.sql
DECLARE
v_Major students.major%TYPE;
v_CourseName VARCHAR2(10);
BEGIN
-
SELECT major
INTO v_Major
FROM students
WHERE ID = 10011;
-
CASE vjlajor
WHEN 'Computer Science' THEN
v_CourseName = 'CS 101';
WHEN 'Economies' THEN
v_CourseName = 'ECN 2 0 3 ' ;
WHEN 'History' THEN
v_CourseName = 'HIS 101';
WHEN 'Music' THEN
v_CourseName = 'MUS 100';
WHEN 'Nutrition' THEN

v_CourseName = 'NUT 307';


ELSE
v_CourseName = 'Unknown';
END CASE;
DBMS_OUTPUT.PUT_LINE(v_CourseName);
END;

test_var, CASE,
, .
,
. test_var
, CASE. ,
_1... test_var.
, CASE. He
break, .

CASE ELSE
ELSE CASE .
,

112

A3

, PL/SQL CASE_NOT_FOUND, ORA-6592, SQL*Plus:


] -- case.sql
SQL> DECLARE
2
v_TestVar NUMBER := 1;
3

BEGIN

1
- WHEN 1,
5
- ORA-6592.
6
CASE v_TestVar
7
WHEN 2 THEN DBMS_OUTPUT.PUT_LINE('Two!');
8
WHEN 3 THEN DBMS_OUTPUT.PUT_LINE('Three!');
9
WHEN 4 THEN DBMS_OUTPUT. PUT_LINEC Four! ');
10 END CASE;
11 END;
12 /
DECLARE
*

ERROR at line 1:
ORA-06592; CASE not found while executing CASE statement
ORA-06512: at line 6
ELSE:
]

ELSE RAISE CASE_NOT_FOUND;

, , 7.

CASE
PL/SQL, CASE . (. ). CASE , END CASE,
:
rj case.sql
DECLARE
v_TestVar NUMBER := 1;
BEGIN
- CASE
MyCase
CASE v_TestVar
WHEN 1 THEN DBMS_OUTPUT.PUT_LINE('One! ');
WHEN 2 THEN DBMS_OUTPUT.PUT_LINE('Two!');
WHEN 3 THEN DBMS_OUTPUT.PUT_LINE('Three!');
WHEN 4 THEN DBMS_OUTPUT.PUT_LINE('Four!');
END CASE MyCase;

END;

END CASE ,
CASE , .

PL/SQL

113

CASE
CASE WHEN
. CASE ,
:
CASE
WHEN testl THEN __1;
WHEN fest2THEN __2;
WHEN testa THEN __;
[ELSE _1;]
END CASE;
;
WHEN . IF-THEN,
TRUE, . CASE . ,
.
Q

case.sql
SQL> DECLARE
2
v_Test1 NUMBER := 2;
3
v_Test2 VARCHAR2(20) := ' G o o d b y e ' ;
4 BEGIN
5
CASE

6
7
8
9
10
11

WHEN v_Test1 = 1 THEN


DBMS_OUTPUT.PUT_LINE('One! ');
DBMS_OUTPUT.PUT_LINE('Another one! ');
WHEN v_Test1 > 1 THEN
DBMS_OUTPUT.PUT_LINEC> 1 ! ' ) ;
DBMS_OUTPUT.PUT_LINE('Still > 1! ' ) ;

12
WHEN v_Test2 = 'Goodbye!' THEN
13
DBMS_OUTPUT.PUT_LINEfGoodbye! ');
14
DBMS_OUTPUT.PUT_LINE('Adios! ');
15
ELSE
16
DBMS_OUTPUT.PUT_LINE('No match');
17
END CASE;
18 END;
19 /
> 1!
Still > 1!

PL/SQL procedure successfully completed.

WHEN, . : v_Test2 'Goodbye' , , WHEN ,


, TRUE.

A3

114

PL/SQL (loops). . , WHILE


FOR . FOR 6.


( ) :
LOOP
_;
END LOOP;
, . , EXIT (),
:
EXIT [WHEN ]
, temp_table
50 :
) simple.sql
DECLARE

v_Counter BINARY_INTEGER := 1;
BEGIN
LOOP
- temp_table
- .
INSERT INTO temp_table
VALUES (v_Counter, 'LOOP index');
v_Counter := v_Counter + 1;
- : : > 50,
- .
IF v_Counter > 50 THEN
EXIT;
END IF;
END LOOP;

END;

EXIT WHEN

IF THEN
EXIT;
END IF;

PL/SQL

115

, :
} exitwhen.sql
DECLARE
v_Counter BINARY_INTEGER := 1;
BEGIN
LOOP
- temp_table
- .
INSERT INTO temp_table
VALUES (v_Counter, 'Loop index');
v_Counter := v_Counter + 1;
- : > 50,
- .

EXIT WHEN v_Counter > 50;


END LOOP;
END;

WHILE
WHILE ( ) :
WHILE LOOP
_ ;
END LOOP;
() .
, .
NULL-,
, END LOOP. ,
WHILE:
| while"!. sql
DECLARE
v_Counter BINARY_INTEGER := 1;
BEGIN
-
- , 50.
WHILE v_Counter <= 50 LOOP
INSERT INTO temp_table
VALUES (v_Counter, 'Loop index');
v_Counter ;= v_Counter + 1;
END LOOP;
END;

, WHILE EXIT * EXIT WHEN.


, ,
.

116

v_Counter, v_Counter <= 50


NULL- temp_table
:
] while2.sql
DECLARE

v_Counter BINARY_INTEGER;
BEGIN
- NULL,
- v_Counter NULL-.
WHILE v_Counter <= 50 LOOP
INSERT INTO temp_table
VALUES (v_Counter, 'Loop index');
v_Counter := v_Counter + 1;
END LOOP;
END;
FOR
WHILE , .
FOR . FOR :
FOR _IN [REVERSE] _,.. _1)
_ ;
END LOOP;
_ , _
'_ , _ .
, . 1 ,
. FOR:
[_) forloop.sql
BEGIN
FOR v_Counter IN 1 . . 5 0 LOOP
INSERT INTO temp_table
VALUES (v_Counter, 'Loop Index');
END LOOP;
END;

, ()
FOR BINARY_INTEGER. . , ,
:
rj forscope.sql
DECLARE
v_Counter NUMBER := 7;

PL/SQL

117

BEGIN
- 7 temp_table.
INSERT INTO temp_table (num_col)
VALUES (v_Counter);
- v_Counter BINARY_INTEGER,
- v_Counter NUMBER.
FOR v_Counter IN 20..30 LOOP
- v_Counter 20 30.
INSERT INTO temp_table (num_col)
VALUES (v_Counter);
END LOOP;
- 7 temp_table.
INSERT INTO temp_table (num_col)
VALUES (v_Counter);
END;
REVERSE FOR
REVERSE ( ), . , -
:
Q

BEGIN

FOR v_Counter IN REVERSE 10..50 LOOP


- v_Counter 50 1.
NULL;
END LOOP;

END;


. , . :
Q DECLARE
v_LowValue NUMBER := 10;
v_HighValue NUMBER := 40;
BEGIN
FOR v_Counter IN REVERSE v_LowValue . . vJHighValue LOOP
INSERT INTO temp_table
VALUES (v_Counter, 'Dynamically specified loop ranges');
END LOOP;
END;

GOTO
PL/SQL GOTO (
). :
GOTO

118

, PL/SQL. . GOTO ,
. :
Q - goto.sql
DECLARE
v_Counter BINARY_INTEGER := 1;
BEGIN
LOOP
INSERT INTO temp_table
VALUES (v_Cour,ter, ' Loop count');
v_Counter := v_Counter + 1;
IF v_Counter > 50 THEN
GOTO !_EndOfLoop:
END IF;
END LOOP;
!_EndOfLoop

INSERT INTO temp_table (char_col^


VALUES ('Done!');

END;

GOTO
PL/SQL GOTO
.
, IF. :
Q BEGIN

GOTO l_InnerBlock; -- ,
-
BEGIN
l_InnerBlock

END;
GOTO l_lnsidelf;

- ,
- IF

IF > 3 THEN
l_lnsidelf
INSERT INTO . . .
END IF;
END;

, IF
, IF . ,
, INSERT , = 2.
, IF :

PL/SQL

119

BEGIN
IF x > 3 THEN
GOTO l_NextCondition;
ELSE
l_NextCondition
END IF;
END;

,
. 7.
Q

DECLARE
v_Room rooms%ROWTYPE;
BEGIN
- rooms.
SELECT *
INTO v_Room
FROM rooms
WHERE rowid = 1;
l_Insert
INSERT INTO temp_table (char_col)
VALUES ('Found a row! ');
EXCEPTION
WHEN NO_DATA F*OUND THEN
GOTO l_Insert; - ,
-
END;


. EXIT , . :
Q

BEGIN
l_0uter
FOR v_0uterlndex IN 1.. 50 LOOP
l_Inner
FOR v_lnnerlndex IN 2.. 10 LOOP
IF v_0uterlriex > 40 THEN
EXIT l_0uter; -
END IF;
END LOOP l_Inner;
END LOOP l_0uter;

, END
LOOP, .

120

A 3

GOTO
GOTO .
GOTO :
, .
GOTO
PL/SQL,
.
.
.

NULL
,
. NULL,
;
. :
| - null.sql
DECLARE
v_TempVar NUMBER := 7;
BEGIN
IF v_TempVar < 5 THEN
INSERT INTO tempjtable (char_col)
VALUES ('Too small1);
ELSIF vJTempVar < 20 THEN
NULL; --
ELSE
INSERT INTO temp_table (char_col)
VALUES (Too big 1 );
END IF;
END;

(pragma) ,
#def ine .
PL/SQL, . , RESTRICT_REFERENCES ( )
SQL- (. 10). , , .
,
PL/SQL Ada.

PL/SQL
(NUMBER, VARCHAR2, DATE ..) STANDARD.

PL/SQL

121

. , .
,
(. ).
PL/SQL . ,
. :
[_J

DECLARE
v_StudentID NUMBER(5);
v_FirstName VARCHAR(20);
v_LastName
VARCHAR2(20);

, students.
, . :
[_j

DECLARE
/* */
TYPE t_StudentRecord IS RECORD (
StudentID
NUMBER(5),
FirstName VARCHAR2(20),
LastName
VARCHAR2(20));
/* */
v_Student!nfo t_StudentRecord;

:
TYPE recvrd_typeIS RECORD (
fieldl typel [NOT NULL] [:= exprl],
field2 type2 [NOT NULL] [:= exprZ],
fieldn typen [NOT NULL] [:= exprn],
record_type , fieldl ... fieldn ,
type! ... typen .
.
, , NOT
NULL . exprl ... exprn
. ,
NOT NULL . ^SampleRecord :
) DECLARE
TYPE t_SampleRecord IS RECORD (
Count
NUMBER(4),
Name
VARCHAR(IO) := 'Scott',
EffectiveDate
DATE,
Description
VARCHAR2(45) NOT NULL := 'Unknown');

122

v_Sample1
v_Sample2

t_.SampleRecord;
t_.SampleRecord;

, ,
NOT NULL,
.
NULL. DEFAULT, :=
.
:
_. _
, v_Sample1 v_Sample2:
F_j BEGIN

/* SYSDATE ,
*/
v_Sample1.EffectiveDate := SYSDATE;
v_Sample2.Description := 'Pesto Pizza';

END;

(rvalue)
.


,
. , v_Sample1 v_Sample2 :
3 v_Sample1 := v_Sample2;

v_Sample1 v_Sample2. ,
, .
"PLS-382: expression is of wrong
type" ( ):
Q - RecordAssignment. sql
DECLARE
TYPE t_Rec1Type IS RECORD (
Field! NUMBER;
Field2 VARCHAR2(5));
TYPE t_Rec2Type IS RECORD (
Field"! NUMBER;
Field2 VARCHAR2(5));
v_Rec1 t_Rec1Type;
v_Rec2 t_Rec2Type;
BEGIN
/* v_Rec1 v_Rec2 ;
. ,

PL/SQL

123

PLS-382. */
v_Rec~l := v_Rec2;
/* ,
. */
v_Rec1.Field1 := v_Rec2.Field1;
v_Rec2.Field2 := v_Rec2. Field2;
END;

SELECT.
. , .
:
RecordSelect.sql
DECLARE

- students.
- %TYPE .
TYPE t_StudentRecord IS RECORD (
FirstName students.first_name%TYPE;
LastName students.last_name%TYPE;
Major students.major%TYPE);
-
v_Student t_StudentRecord;
BEGIN
- ID, 10000.
- , ,
-- v_Student.
SELECT first_name, last_name, major
INTO v_Student
FROM students
WHERE ID = 10000;
END;

Oracle9z INSERT
UPDATE (. 4).

%ROWTYPE
PL/SQL
, . PL/SQL
%ROWTYPE. %TYPE, %ROWTYPE
. , ,
[_j DECLARE
v_RoomRecord rooms%ROWTYPE;

, rooms.
, v_RoomRecord :

124

(room_id
building
Voom_number
number_seats
description

NUMBER(5),
VARCHAR2(15),
NUMBER(4),
NUMBER(4),
VARCHAR2(50))

%TYPE, NOT NULL,


. VARCHAR2 CHAR, a
NUMBER .
, %ROWTYPE
. %TYPE, %ROWTYPE ,
PL/SQL,
, .

PL/SQL
- . ,
, , , .
, , .
, , .
, , , . ,
,
.
,
.
PJ declare
number;
number;
begin if < 10 then := 7; else := 3; end if; end;
DECLARE

v_Test NUMBER;
-,
v_Result NUMBER;
-
BEGIN
- v_Test. v_Result 7, v_Test < 10.
IF v_Test < 10 THEN
v_Result := 7;
ELSE
v_Result := 3;
END IF;
END;
, .

PL/SQL

125

, .
. PL/SQL.

,
. :
/ . , (). , ,
( )
( ).
, , . .
. ,
. ,
:
[_J

V_SSN CHAR(11);

--Social Security Number


- ( )

, . , , .
, , .
, .
:
" , ?" ,
- !
,
. , , , PL/SQL, :
3 DECLARE
v_Temp NUMBER := 0; -- v_Temp
,
v_Temp:
]

DECLARE

126

v_Temp NUMBER := 0;

- ,


.
_)

number;

, .
)

v_StudentID NUMBER(5);

, , ,
. , PL/SQL 30
.
.
. : , . :
] v_VariableName
e_ExceptionName
t_TypeName
p_ParameterName
c_ConstantValue


,
,

, CONSTANT ()


PL/SQL . . :
(, BEGIN, DECLARE, ELSIF).
(SUBSTR,
COUNT, TO_CHAR).

(NUMBER(7,2), BOOLEAN, DATE).
SQL (SELECT,
INTO, UPDATE, WHERE).
(log_table, classes,
students).
'.
; (v_HireDate,
e_TooManyStudents, t_StudentRecordType).

PL/SQL

127


, , ( , ). .
IF-THEN-ELSE:
)

IF < THEN IF z IS NULL THEN x := 3; ELSE x := 2; END IF; ELSE


x := 4; END IF;
IF x < THEN
IF z IS NULL THEN
x := 3;
ELSE
x := 2;
END IF;
ELSE
x := 4;
END IF;

:
; DECLARE..END; . , SQL-,
, :
_| SELECT id, first_name, last_name
INTO v_StudentID, V_FirstName, v_LastName
FROM STUDENTS
WHERE id = 10002;


PL/SQL , ,
. . . ,
, , .
, ,
, , , PL/SQL. PL/SQL.
-
, , , PL/SQL.

128

PL/SQL:
PL/SQL, (, -,
), , . ,
PL/SQL, . SQL- .
8.

4
SQL PL/SQL

ABA 4

130

. (SQL, Structured Query Language)


Oracle. , ,
,
SQL, PL/SQL Oracle. , SQL- PL/SQL
.
SQL- 5.

SQL
SQL . 4.1
, .
SQL- "Server SQL
Reference".
(DML,
Data Manipulation Language) , , .
(DDL, Data Definition Language) ,
. DDL , .
. SQL- , ,
.
, ,
SQL .
, , ,
.

SQL PL/SQL

131


.
. , SQL *Plus
, spool ( )
set serveroutput (
DBMS_OUTPUT ). *
SQL, allocate (
) connect (
).
2.

4.1. SQL-

SQL-

(DML)

SELECT, INSERT, UPDATE, DELETE, EXPLAIN PLAN

(DDL)

DROP, CREATE, ALTER, GRANT, REVOKE

COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION

ALTER SESSION, SET ROLE

ALTER SYSTEM

SQL PL/SQL
SQL- PL/SQL
DML .
DDL . EXPLAIN PLAN ( )
DML . , PL/SQL.

, . (binding)
, .
PL/SQL , .
, (early binding), , , (late binding),
. ,
( ), ,
. , .
PL/SQL
,
. , PL/SQL

132

, , . , ..
(. 9 -^ 11). DDL. DDL , ,
.
,
.

PL/SQL:
Q

BEGIN

CREATE TABLE tempjtable (


num_value NUMBER,
char_value CHAR(10));
INSERT INTO temp_table (num_value, char_value)
VALUES (10, 'Hello');
END;
,
temp_table. , . , . , .
DML SQL,
, PL/SQL SQL-.

SQL
,
PL/SQL SQL, DDL. SQL. SQL ,
,
. , PL/SQL , .
SQL PL/SQL: SQL (18' )
DBMS_SQL. ,
SQL CREATE TABLE, . INSERT ,
.
SQL. SQL temp_table
:
)

BEGIN

EXECUTE IMMEDIATE 'CREATE TABLE temp_table (


num_value NUMBER,

133

SQL PL/SQL
char_value CHAR(10))';
EXECUTE IMMEDIATE 'INSERT INTO temp_table (num_value, char_value)
1
VALUE(10, "Hello") ;
END;

SQL
12.

DML PL/SQL
DML SELECT (), INSERT
(), UPDATE () DELETE ().
: SELECT , WHERE;
INSERT ; UPDATE
, WHERE;
DELETE . WHERE, (. ).
SQL- SQL*Plus,
(. . 4.1). UPDATE, INSERT DELETE
SQL*Plus , SELECT
, .
l4kOiacleSQL"Plus
HHQI
*.^^^^^^^^^^^^^*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File Edit Search Options Help

jd

SQL> SELECT first name, last name, major


2
FROM students
3
ORDER BV major;
FIRST_NftME

LAST_NAME

MAJOR

Scott
Joanne
Manish
Barbara
Margaret
Patrick
Timothy
Dauid
Rose
Ester
Rita

Smith
Junebug
Murgratroid
Blues
Mason
Poll
Taller
Dinsmore
Riznit
Elegant
Razmataz

Computer Science
Computer Science
Economics
Economics
History
History
History
Music
Music
Nutrition
Nutrition

11 rows selected.
SQL> UPDATE CLASSES

2
3

SET num credits - 3


WHERE department = 'HIS'

AND course - 181;

1 row updated.
SQL> commit;
Commit complete.
SQL>

JLJJ
. 4.1. SQL- SQL*Plus

134

UPDATE, . 4.1:
UPDATE CLASSES
SET num_credits = 3
WHERE department = 'HIS'
AND course = 101;

, classes,
, .. . PL/SQL .
SQL-, . , , (bind variable).
, UPDATE
, , :

- BindVariable.sql
DECLARE
v_NumCredits classes.num_credits%TYPE;
BEGIN
/* v_NumCredits */
v_NumCredits := 3;
UPDATE CLASSES
SET num_credits = v_NumCredits
WHERE department = 'HIS'
AND course = 101;
END;

.
SQL- .
, .
, Oracle
. , . , SQL.

SELECT
SELECT PL/SQL. SELECT
.
SELECT

> INTO

-jf- __ -i

, -4
.I

<--> __ ^J
t
.
1
1

* 3arwcb_PL/SQL ,

1
Lw WHERE
WUCRF

* FROM

j>
k.
*-
M/HFBFJ
WHERE-

SQL PL/SQL

135

.
SELECT

__ ( ).

.
(select list).
* .

, .

PL/SQL, .

.
.

3anncb_PL/SQL

.
, .
.

,
(. 3).
*,
__%\.

__

, .
,
.
. __
.
, ,
, ,
(!/ ) inline- (.
" "),

WHERE

, ,
. WHERE
,
(. " WHERE").

SELECT
, ORDER BY ( ) GROUP
BY ( ). SELECT
, UNION MINUS.

Server SQL Reference".
SELECT, ,
.
,
, PL/SQL :

136

Q ORA-1427: Single-row query returns more than one row


( )


(. 6).
SELECT:
)

-- select.sql
DECLARE

v_StudentRecord
students%ROWTYPE;
v_Department
classes.department%TYPE;
v_Course
classes.course%TYPE;
BEGIN
- students
- v_StudentRecord. ,
- WHERE .
-
- students ( *), ,
- , students%ROWTYPE.
SELECT *
INTO v_StudentRecord
FROM students
WHERE id = 10000;
- classes
- v_Department v_Course. WHERE
- .
SELECT department, course
INTO v_Department, v_Course
FROM classes
WHERE room_id = 20003;
END;

INSERT
INSERT . ,
WHERE.
-> INSERT

( . > _

VALUES

* INTO

* __-

SQL PL/SQL

137

___ Oracle, _
, SQL
PL/SQL, . . INSERT
_, ,
. , SQL.

-:"

SELECT, INSERT .
,
VALUES (. "Server SQL Reference").

INSERT:
- insert, sql
DECLARE
v_StudentID students.id%TYPE;
BEGIN
- .
SELECT student_sequence.NEXTVAL
INTO v_StudentID
FROM dual;
- students.
INSERT INTO students (id, first_name, last_name)
VALUES (v_StudentID, 'Timothy', 'Taller');
- ,
- INSERT.
INSERT INTO students (id, first_name, last_natne)
VALUES (student_sequence.NEXTVAL, 'Patrick', 'Poll');
END;

INSERT,
, . : "ORA-913:
Too many values" ( ).
INSERT INTO rooms
SELECT * FROM classes;

. temp_table:
INSERT INTO temp_table
SELECT * FROM temp_table
OracleS, ,
INSERT REF INTO.
, (. 12).

138

UPDATE
UPDATE :
* UPDATE

* __

>=

WHERE |

> SET

>

>
> _

> ycnoene_where
CURRENT OF

'

__ ( ), _ , , SQL, 3.
_, SET (). 'CURRENT OF '
(. 6).
UPDATE:
Q update.sql
DECLARE

v_Major
students.majr%TYPE;
v_Credit!ncrease NUMBER := 3;
BEGIN
- UPDATE
- current_credits ,
- , 3.
v_Major := 'History';
UPDATE students
SET current_credits = current_credits + v_Credit!ncrease
WHERE major = V_Major;

- UPDATE temp_table
-
UPDATE temp_table
SET num_col = 1, char_col = 'abed';
END;
DELETE
DELETE . WHERE , . DELETE
.

SQL PL/SQL

139

-> DELETE |
1

WHERE

> FROM

> __ -

* ycnoene_where

'* CURRENT OF

__, Oracle (
), a ycAoeue_where ,
. 'CURRENT OF '
(. 6).
WHERE .
,
DELETE:
- delete.sql
DECLARE
v_StudentCutoff NUMBER;
BEGIN
v_StudentCutoff := 10;
- ,
-- .
DELETE FROM classes
WHERE current_students < v_StudentCutoff;
- -,
-- .
DELETE FROM students
WHERE current_credits = 0
AND major = 'Economies';

END;

DELETE ,

,
tables, sql.
classes.

"Server SQL Reference".

WHERE
SELECT, UPDATE DELETE WHERE. (active set) , SELECT UPDATE DELETE.
WHERE ,
AND (), OR () NOT ().
, :

140

Q -- WhereClause.sql
DECLARE

v_Department CHAR(3);
BEGIN
v_Department := ' C S ' ;
-
DELETE FROM classes
WHERE department = v_Department;
END;

classes, (.. department 'CS').


, .


,
v_Department department:
PJ WhereClause.sql
DECLARE

Department CHAR(3);
BEGIN
Department := ' C S ' ;
-
DELETE FROM classes
WHERE department = Department;
END;

: classes ,
, 'CS'! SQL- . PL/SQL
Q 1 = 2
,
.
PL/SQL . PL/SQL , department, Department classes, .
, .
, , ,
. ,
, .. , department = 'CS'.
Q - WhereClause.sql
l_DeleteBlock
DECLARE

SQL PL/SQL

141

Department CHAR(3);
BEGIN
Department := ' C S ' ;
-
DELETE FROM classes
WHERE department = l_DeleteBlock.Department;
END;

,
PL/SQL
(. 3).

Oracle
: .
. ,
s t r i n g l string2. :
1. ,
, .
2. , . ,
c h a r l stringl char2 string2.
3. ASCII(charl) < ASCII(char2), s t r i n g l < s t r i n g 2 .
ASCII(charl) > ASCII(char2), s t r i n g l > string2. ASCII(charl) =
ASCII(char2), s t r i n g l string2.
4. , .
:
)

'abc' = ' a b c '


'abc ' = ' a b c '
' a b ' < 'abc'
'abed' > 'abcc'

- ,


:
1. , . ,
charl s t r i n g l c h a r 2 string2.
2. ASCII(charl) < ASCII(char2), s t r i n g l < s t r i n g 2 .
ASCII(charl) > ASCII(char2), s t r i n g l > string2. ASCII(charl)
= ASCII(char2), s t r i n g l string2.
3. s t r i n g l string2, s t r i n g l <
string2. s t r i n g 2 s t r i n g l ,
stringl > string2.

4. , .

142

:
_|

'abc' = 'abc'
' a b ' < 'abc'
'abed' > 'abcc'

, , ,
. .
) 'abc

' = 'abc'

- .

? PL/SQL ,
.
, . CHAR , VARCHAR2 . ,
( ) .
, , . WHERE.
, ,
v_Department VARCHAR2, CHAR.
)

WhereClause.sql
DECLARE

v_Department VARCHAR2(3);
BEGIN
v_Department := ' C S ' ;
-
DELETE FROM classes
WHERE department = v_Department;
END;

department classes CHAR.


department 'CS ' (
). v_Department 'CS' ( ), , DELETE
.
WHERE ,
PL/SQL ,
, . , %TYPE.


SQL PL/SQL SQL.
SQL
PL/SQL. , :

SQL PL/SQL

143

-- bulkDeno.sql
DECLARE
TYPE t_Numbers IS TABLE OF temp_table. num_col%TYPE
INDEX BY BINARY_INTEGER;
TYPE t_Chars IS TABLE OF temp_table.char_col%TYPE
INDEX BY BINARY_INTEGER;
v_Numbers t_Numbers;
v_Chars t_Chars;
BEGIN
-- 500
FOR v_Count IN 1..500 LOOP
v_Numbers(v_Count) := v_Count;
v_Chars(v_Count) := 'Row number' || v_Count;
END LOOP;
-
FOR v_Count IN 1..500 LOOP
INSERT INTO temp_table VALUES
(v_Numbers(v_Count), v_Chars(v_Count));
END LOOP;
END;

PL/SQL,
Java.

8.
temp_table 500 .
INSERT . 500
PL/SQL SQL.
OracleSi , PL/SQL SQL ,
(bulk bind).
FORALL, :
bulkOemo.sql
DECLARE
TYPE t_Numbers IS TABLE OF temp_table. num_col%TYPE
INDEX BY BINARY_INTEGER;
TYPE t_Chars IS TABLE OF temp_table. char_col%TYPE
INDEX BY BINARY_INTEGER;
v_Numbers t_Numbers;
v_Chars t_Chars;
BEGIN
- 500
FOR v_Count IN 1. .500 LOOP
v_Numbers(v_Count) := v_Count;
v_Chars(v_Count) := 'Row number ' || v_Count;
END LOOP;

144


FORALL v_Count IN 1..500
INSERT INTO temp_table VALUES
(v_Numbers(v_Count), v_Chars(v_Count));
END; '

(. 12).

RETURNING
,
DML, , rowid .
. SELECT
DML. SQL
RDBMS. OracleS : RETURNING.
DML, . RETURNING:
> RETURNING!

- , *|

^*
"-->
'4 INTO *
->

PL/SQL SQL, , PL/SQL,


. .
(, ROWID,
"".) SQL*Plus RETURNING:
| Returninglnto.sql
SQL> DECLARE

2
v_NewRowid ROWID;
3 v_FirstName students. first_name%TYPE;
4 v_Last_Name students. last_name%TYPE;
5 v_ID students. ID%TYPE;
6 BEGIN
- students
8
- rowid .
9
INSERT INTO students
10
(ID, first_name, last_name, major, current_credits)
11
12
13
14
15
16

VALUES
(student_sequence.NEXTVAL, ' X a v i e r ' , 'Xemes', 'Nutrition', 0)
RETURNING rowid INTO v_NewRowid;

17
Iff

- , ,
-

DBMS_OUTPUT,PUT_LINECNewly inserted rowid is ' 1 1 v_NewRowid);

SQL PL/SQL

19

145

UPDATE students

20
21
22

SET current_credits = current_credits + 3


WHERE rowid = v_NewRowid
RETURNING first_name, last_name INTO v_FirstName, v_LastName;

23

24 DBMS_OUTPUT.PUT_LINE('Name: ' || v_FirstName || " || v_LastName);


25
26
- ID
27 DELETE FROM students
28
WHERE rowid = v_NewRowid
29
RETURNING ID INTO v_ID;
30
31 DBMS_OUTPUT.PUT_LINE('ID of new row was ' || v_ID);
32 END;
33 /
Newly inserted rowid is AAAF3MAAFAAAAATAAM
Name: Xavier Xemes

ID of new row was 10012

PL/SQL procedure successfully completed.


DML . :
[.] \@ __]

, ___ ,
.
,
. SQL-, ,
. , :
)

UPDATE students
SET major = 'Music'
WHERE id = 10005;

( students) , , .
, :
] ORA-942: table or view does not exist
( )

] PLS-201: identifier must be declared


( )

146

,
- SQL PL/SQL.
,
, :
UPDATE example.students
SET major = 'Music'
WHERE id = 10005;

UPDATE , example , UPDATE students.

Orac/eSi
TABLEf),

(. 8). Oracle9't

(. 12).


SQL*Net,
. (database link) , , .
DDL:
CREATE DATABASE LINK _
CONNECT TO _ IDENTIFIED BY
USING sqlnet_cmpoKa;
, . , a sqlnet_cmpoK(i
. , , SQL*Net .
:
CREATE DATABASE LINK example_backup
CONNECT TO example IDENTIFIED BY example
USING 'backup_database';


SQL*Net "SQL*Net User's Guide and Reference". students:
UPDATE students@exarople_backup
SET major = 'Music'
WHERE id = 10005;

SQL PL/SQL

147

, (distributed transaction),
. ,
"Server SQL
Reference".

,
/ . Oracle . (synonym), , ,
, (alias) .
DDL- CREATE SYNONYM:
CREATE SYNONYM _ FOR ',
_ ,
. , , . :
) CREATE SYNONYM backup_students
FOR students@example_backup;

UPDATE:
Q UPDATE backup_students
SET major = 'Music'
WHERE id = 10005;

>:

- ,
;
.

(pseudocolumns) ,
SQL-. , .
SQL-.

CURRVAL NEXTVAL
CURRVAL ( ) NEXTVAL (
) . (sequence) Oracle,

148

. DDL- CREATE SEQUENCE. ,


:
. URRVAL

nocnedoeamenbHocmb.NEKTVAL
. CURRVAL , a NEXTVAL
. CURRVAL, NEXTVAL , NUMBER. CURRVAL NEXTVAL.
, VALUES INSERT SET UPDATE.
WHERE PL/SQL. CURRVAL NEXTVAL:
] tables.sql
CREATE SEQUENCE student_sequence
START WITH 10000
INCREMENT BY 1;

-
10000.
INSERT INTO students (id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, ' S c o t t 1 , 'Smith',
'Computer Science', 11);
-
-- 10001.
INSERT INTO students (id, first_name, last_name, major,
current_credits)
VALUES (student_sequence.NEXTVAL, 'Margaret', 'Mason',
'History', 4);

SQL*Plus CURRVAL
(, 12- students tables, sql):
Q SQL> SELECT student_sequence.CURRVAL
2
FROM dual;
CURRVAL

10011

SQL PL/SQL

149

LEVEL
LEVEL () SELECT , START WITH ( ) CONNECT BY ( ).
LEVEL NUMBER.
"Server SQL Reference".

ROWID
ROWID ( )
.
ROWID (. 3). ROWTD ROWID. , rooms:
Q

SQL> SELECT ROWID


2
FROM rooms;
ROWID
AAAF3PAAFAAAABDAAA
AAAF3PAAFAAAABDAAB
AAAF3PAAFAAAABDAAC
AAAF3PAAFAAAABDAAD
AAAF3PAAFAAAABDAAE
AAAF3PAAFAAAABDAAF
AAAF3PAAFAAAABDAAG
AAAF3PAAFAAAABDAAH
AAAF3PAAFAAAABDAAI
9 rows selected.

ROWID, Oracle? OracleS, .


( 18\)
. , ,
Oracle, ,
ROWID. ROWID
(. 3).

ROWNUM
ROWNUM .

WHERE SET
UPDATE. , ROWNUM, NUMBER. , students:
SELECT *
FROM students

150

WHERE ROWNUM < 3;

ROWNUM 1, ROWNUM 2 ..
ROWNUM
( ORDER BY).
ROWNUM ,
. :
rj SELECT first_name, last_name
FROM students
WHERE ROWNUM < 3
ORDER BY first_name;

students, first_name.
, . , (. 6).
(inline) ORDER
BY (. "Server SQL Reference").

GRANT, REVOKE
DDL, GRANT () REVOKE (),
PL/SQL, SQL-. Oracle , INSERT
DELETE, , SQL- GRANT REVOKE.


: .
(object privilege) (, ). (system privilege)
.
4.2 .
DDL ALTER (), INDEX (), REFERENCES ()
PL/SQL ( SQL),
DDL .
,
DDL. ,
CREATE TABLE .
CREATE ANY TABLE
. "Server SQL Reference".

151

SQL PL/SQL

4.2. SQL

ALTER

DELETE

, ,


ALTER
(, ALTER TABLE).


DELETE.

PL/SQL
(. 9 11).


CREATE INDEX.

INSERT.

EXECUTE
INDEX

INSERT

ON COMMIT
REFRESH2

QUERY
REWRITE2

READ1

REFERENCES
SELECT
UNDER3

UPDATE

, ,
,

OracleS
Oracleffi
Oracle9i



,
commit.


,
.

.

,
.

SELECT.

,

.


UPDATE.

152

GRANT REVOKE
GRANT ,
REVOKE , GRANT.
, .

GRANT
GRANT :
GRANT ON _
[WITH GRANT OPTION];
, ,
, _ ,
. , userA . GRANT :
| GRANT SELECT ON classes TO userA;

WITH GRANT OPTION (


), userA . GRANT , :
| GRANT UPDATE, DELETE ON students TO userA;

GRANT :
GRANT _ [WITH ADMIN OPTION];
, _ , .
WITH ADMIN OPTION ( ), _ . :
] GRANT CREATE TABLE, ALTER ANY PROCEDURE TO userA;

,
GRANT .
GRANT DDL,
, ,
(COMMIT) .

REVOKE
REVOKE :
REVOKE ON FROM _
[CASCADE CONSTRAINTS] [FORCE];
, , , _ , . :

SQL PL/SQL

153

rj REVOKE SELECT ON classes FROM userA;


CASCADE CONSTRAINTS ( ) REFERENCES, ,
. FORCE EXECUTE .
:
| REVOKE UPDATE, DELETE, INSERT ON students FROM userA;

REVOKE :
REVOKE FROM _;
, _ , .
:
| REVOKE ALTER TABLE, EXECUTE ANY PROCEDURE FROM userA;

Oracle, , . Oracle, .
(role) , , , ,
. :
| CREATE ROLE table_query;
GRANT SELECT ON students TO table_query;
GRANT SELECT ON classes TO table_query;
GRANT SELECT ON rooms TO table_query;

table_query SELECT .
:
Q GRANT table_query TO userA;
GRANT table_query TO userB;

SELECT userA
userB. : .
Oracle PUBLIC (), .
Q

GRANT PUBLIC;


Oracle.
Oracle ,
. OracleQz 4.3. Oracle SYSTEM .

154

4.3.

CONNECT

ALTER SESSION, CREATE CLUSTER, CREATE DATABASE LINK, CREATE


SEQUENCE, CREATE SESSION, CREATE SYNONYM, CREATE TABLE,
CREATE VIEW

RESOURCE

CREATE CLUSTER, CREATE INDEXTYPE, CREATE OPERATOR, CREATE


PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE TRIGGER,
CREATE TYPE

DBA

( ADMIN OPTION;
), EXP FULL DATABASE
IMP_FULL_DATABASE

EXP FULL DATABASE

ADMINISTER RESOURCE, BACKUP ANY TABLE, EXECUTE ANY


PROCEDURE, EXECUTE ANY TYPE, SELECT ANY TABLE, INSERT,
UPDATE, DELETE sys. incexp, sys. incvid
sys.incfil

Oracle ,
.

CONNECT () RESOURCE () , ,
, ,
CONNECT. , .


(transaction) SQL-, ( ) .
, . . SQL-,
, transaction_amount, (f rom_acct) (to_acct).
(_J UPDATE accounts
SET balance = balance - transaction_amount
WHERE account_no = from_acct;
UPDATE accounts
SET balance = balance + transaction_amount
WHERE account_no = to_acct;

, UPDATE , (, - ).
f rom_acct,

155

SQL PL/SQL

to_acct. He , ( f rom_acct ).
, . , , .
SQL-,

. COMMIT ROLLBACK.

COMMIT ROLLBACK
COMMIT (),
:
, , .
,
.
, , .
COMMIT:
COMMIT [WORK];
WORK () . , ,
(. 4.2).
INSERT. rooms, , , INSERT .
, SELECT
.

INSERT INTO rooms


(room_id, building, room_number,
number_seats, description)
VALUES

(99991, 'Building 7', 310,


50, 'Discussion Room E');

COMMIT

. 4.2.

SELECT .
FROM rooms
WHERE building = 'Building 7'
SELECT *
FROM rooms
WHERE building = 'Building 7'

156

ROLLBACK (),
:
, , ,
.
, ', .
ROLLBACK:
ROLLBACK [WORK]
COMMIT, WORK
. ROLLBACK
,
.
COMMIT
ROLLBACK, .

SQL*Plus COMMIT,
. ,
(autocommit) COMMIT
SQL-.
SQL- PL/SQL, SOL*Plus
.
SQL*Plus , COMMIT
. ,
SQL*Plus .


, ROLLBACK . SAVEPOINT ( )
. SAVEPOINT:
SAVEPOINT ;
.
,
SQL (. 3). , ,
, .
, :
ROLLBACK [WORK] TO SAVEPOINT ;
ROLLBACK TO SAVEPOINT
:

SQL PL/SQL

157

, , . .
.
, SQL- , , ,
SQL- .
, SQL-
.
PL/SQL:
Q

BEGIN
INSERT INTO temp_table (char_col) VALUES ('Insert O n e ' ) ;
SAVEPOINT A;
INSERT INTO temp_table (char_col) VALUES ('Insert T w o ' ) ;
SAVEPOINT B;
INSERT INTO temp_table (char_col) VALUES ('Insert T h r e e ' ) ;
SAVEPOINT C;
/* */
COMMIT;
END;

ROLLBACK TO ;

INSERT . INSERT .
rj

ROLLBACK TO ;

INSERT
.
SAVEPOINT
. , ,
.


PL/SQL. ,
, . , . ,
SQL*Plus:
Q

INSERT INTO classes


(department, course, description, max_students,
current_students, num_credits, room_id)
VALUES ( ' C S ' , 101, 'Computer Science 101', 50, 10, 4, 99998);
BEGIN
UPDATE rooms

158

SET room_id = room^id + 1;


ROLLBACK WORK;
END;

INSERT,
PL/SQL. , UPDATE
ROLLBACK. ROLLBACK UPDATE, INSERT, , ,
.
PL/SQL
:
DECLARE
v_Num!terations NUMBER;
BEGIN
- 1 500 temp_table.
- 50 .
FOR v_LoopCounter IN 1 . . 5 0 0 LOOP
INSERT INTO temp_table (num_col) VALUES (v_LoopCounter);
v_NumIterations := v_NumIterations + 1;
IF v_NumIterations = 50 THEN
COMMIT;
v_Num!terations := 0;
END IF;
END LOOP;
END;

temp_table
1 500, 50 .
, 10
.


18 ,
SQL
. OracleSz . ,
(-), .
-.

AUTONOMOUSJTRANSACTION
PL/SQL.
, :
- autoTrans.sql
CREATE OR REPLACE PROCEDURE Autonomous AS

SQL PL/SQL

159

PRAGMA
AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO temp_table VALUES (-10, 'Hello from Autonomous!');
COMMIT;
END Autonomous;

9.

PL/SQL , . Autonomous
PL/SQL:
Q - autoTrans.sql
BEGIN
- temp_table -
INSERT INTO temp_table VALUES (-10, 'Hello from the parent! ');
- Autonomous,
-
Autonomous;
-- - Autonomous
--
ROLLBACK;
END;

tempjtable . INSERT - -, INSERT .


] - autoTrans.sql
SOL> SELECT * FROM temp_table WHERE num_col = -10;
NUM COL CHAR COL
-10 Hello from Autonomous!

AUTONOMOUSJTRANSACTION ,
. ,
.
.
:

,

160

, PL/SQL .
.
SQL*Plus . ,
, PLS-710.
-- autoPragna.sql
SQL> -- :
SQL> DECLARE
2
PRAGMA AUTONOMOUS_TRANSACTION;
3 BEGIN
4
COMMIT;
5 END;
6 /
PL/SQL procedure successfully completed.
SQL> -- ;
SQL> BEGIN

2
DECLARE
3
PRAGMA AUTONOMOUS_TRANSACTION;
4
BEGIN
5
COMMIT;
6 END;
7 END;
8 /
PRAGMA AUTONOMOUSJTRANSACTION;
*

ERROR at line 3:
ORA-06550: line 3, column 12:
PLS-00710: PRAGMA AUTONOMOUS_TRANSACTION cannot be declared here
SQL> -- , :
SQL> CREATE OR REPLACE PROCEDURE Autol AS
2
PRAGMA AUTONOMOUS_TRANSACTION;
3

4
PROCEDURE Local IS
5
PRAGMA AUTONOMOUS_TRANSACTION;
6
BEGIN
7
ROLLBACK;
8
END Local;
9 BEGIN
10
Local;
11 COMMIT;
12 END Autol;
13 /
Procedure created.
SQL> show errors
No errors.
SQL> -- :

SQL PL/SQL

161

SQI_> CREATE OR REPLACE PACKAGE Auto2 AS


2
PROCEDURE P;
3 END Auto2;
4 /

Package created.
SQL> show errors
No errors.

SQL> CREATE OR REPLACE PACKAGE BODY Auto2 AS


2 PROCEDURE P IS
3
PRAGMA AUTONOMOUS_TRANSACTION;
4 BEGIN
5
COMMIT;
6

END P;

7 END Auto2;
8 /
Package body created.
SQL> show errors
No errors.
SQL> -- :
SOL> CREATE OR REPLACE PACKAGE Auto3 AS
2
3
4
5

PRAGMA AUTONOMOUS_TRANSACTION;
PROCEDURE P;
PROCEDURE Q;
ENDAutoS;

6/

Warning: Package created with compilation errors.


SQL> show errors
Errors for PACKAGE AUTOS:
LINE/COL

ERROR

2/10

PLS-00710: PRAGMA AUTONOMOUS_TRANSACTION cannot be declared here


'' '.' 9.

SQL COMMIT ROLLBACK.

, COMMIT, ROLLBACK, SAVEPOINT, ROLLBACK
TO SAVEPOINT SET TRANSACTION.
.
, -, :
Q

-- autoSavepoints.sql
SQL> CREATE OR REPLACE PROCEDURE AutoProc AS
2
PRAGMA AUTONOMOUS_TRANSACTION;

162

BEGIN

4
ROLLBACK TO SAVEPOINT A;
5 END AutoProc;
6 /
Procedure created.
SQL> BEGIN
2
SAVEPOINT A;
3
INSERT INTO temp_table (char_col)
A
VALUESCSavepoint A!');
5
- -,
6
- ,
7
- .
8
AutoProc;
9 END;
/
BEGIN
*

ERROR at line 1:
ORA-01086: savepoint ' A ' never established
ORA-06512: at "EXAMPLE.AUTOPROC", line 4
ORA-06512: at line 8


COMMIT ROLLBACK.
. ,
ORA-6519 .
]

- autoTrans.sql
SQL> DECLARE
2
PRAGMA AUTONOMOUS_TRANSACTION;
3 BEGIN

4
INSERT INTO temp_table (num_col) VALUES (1);
5 END;
6 /
DECLARE
*

ERROR at line 1:
ORA-06519: active autonomous transaction detected and rolled back
ORA-06512: at line 4

SQL , DML
, , ,
PL/SQL. , , ,
.
SQL, 6 , .

ids

s vavi/j
|

164

' SQL, 4, .
.

SQL ,
SQL- . , SELECT,
UPPER ( ) , , ,
:
SELECT UPPER(first_name)
FROM students;

SQL- PL/SQL. , UPPER :


Q

DECLARE

v_FirstName students.first_name%TYPE;
BEGIN
v_FirstName := UPPER('Charlie');
END;
SQL- . , UPPER
. ,
PL/SQL (. 3). , SQL-
.
.
HAVING . PL/SQL . COUNT ( ).
, UPPER,
. SQL-, , PL/SQL.
. .
. ([]) .

SQL

165

Oracle?, OracleS,
OracleSl Orac/e9i.

(.. 7.3 Oracle? 8.1.7 OracleSl).
.

,

( CHR NCHR) .
, VARCHAR2; , , . , , ,
, .. VARCHAR2
4000 (2000 Oracle?), CHAR 2000
(255 Oracle?). PL/SQL,
VARCHAR2, CHAR.

CHR(x[USING NCHAR_CS]) Oracle? (USING


SQL-.
NCHAR_CS OracleS) USING_NCHAR_CS
OracleG/
SQL .
, , .
CHR ASCII . CHR
, a ASCII . USING NCHAR_CS
(OracleS ),
. NCHAR (19/ ) CHR USING_NCHAR_CS.
CONCAT(sfring/, string?)

Oracle?

SQL-.

string/ strings. 11.


VARCHAR2 stringl.
INITCAP(sfring)

Oracle?

SQL-.

, ,
. -
. , , .
, string.
LOWER(strmg)

Oracle?

SQL-.

, . , ,
. string CHAR, CHAR. string
VARCHAR2, VARCHAR2.
LDAPfstring/, x[, string?])

Oracle?

SQL-.

166

string 7, string2.
string? , . string2
, sfring2. string2 ,
. ,
, .
, .
LDAP RDAP , , .
LTRIM(string/, sfring2)

Oracle?

SQL-.

string/ , string2.
string2 .
string?, . ,
sfring2, . LTRIM RTRIM ,
, .
REPLACE(string, searcn_sfr Oracle?
[, replacejstr])

SQL-.

, searcn_str replace_str.
replacejtr , searchjtr . REPLACE
, TRANSLATE.
RPAD(sfring/, x[, string2J)

Oracle?

SQL-.

string/ string?.
string2 , . string2 ,
. string? ,
. , ,
. ,
. RPAD LPAD
, , .
RTRIM(string/ [,stringh2])

Oracle?

SQL-.

string/ ,
string?. string? .
string/, . ,
string?, . RTRIM LTRIM
, , .
SOUNDEX(sfring)

Oracle?

SQL-.

string (. ).
SUBSTR(sfring, a [,b])

Oracle?

SQL-.

string; b (. ).
SUBSTRB(string, a[,b])

Oracle?

SQL-.

string; b (. ).
SUBSTRCfsfring, a[,b])

!9/

SQL-.

string; b Unicode (. ).
SUBSTR2(string, a[,bj)

Oracle9/

SQL-.

string; b UCS2 (. ).

SQL

SUBSTR4(string, a[,b])

Oracle9i

SQL-.

167

string; b UCS4 (. ).
TRANSLATE(sfring,
fromjtr, tojtr)

Oracle?

SQL-.

sfring, from_str
fo_sfr. TRANSLATE
, REPLACE. fromjtr fo_sfr,
fromjstr, fo_sfr, sfring,
. fo_sfr . Oracle NULL,
- TRANSLATE NULL, NULL.
TRIM([{{LEADING|TRAILING OracleSi
|BOTH}[frim_char]) |
trim_char} FROM] sfring)

SQL-.

sfring trim_char / . Trim_char


, .
LEADING, TRAILING BOTH, trim_char
sfring.
UPPER(sfring)

Oracle?

SQL-.

, .
CHAR, CHAR. VARCHAR2,
VARCHAR2. , ,
.

SUBSTR, SUBSTRB, SUBSTRC, SUBSTR2 SUBSTR4

SUKSTR(string, [,
,

string,
b . = 0, , = 1 ( ). , . ,
, , .
b , . b 1, NULL-.
b , .
, string.
SUBSTR b ,
.

168

SUBSTR

SUBSTRB

SUBSTRC

UNICODE

SUBSTR2

USC2

SUBSTR4

USC4

| SELECT SUBSTRCabc123def , 4, 4) "First"


FROM dual;
First

123d

SELECT SUBSTRCabc123def, -4, 4) "Second"


FROM dual;
Second
3def
SELECT SUBSTR(-abc123def, 5) "Third"
FROM dual;
Third
23def

SOUNDEX

SOUNDEX(s*nng)
string.
, , .
. "The Art of Computer Programming, Volume 3:
Sorting and Searching".
:
, , h, i, ,
wviy.
:
1. b,f,p,v
2. , g,j, k, q, s, x, z
3. d,t
4. /

SQL

169

5. ,
6.
(, j) h w,
, .
4 , .

| SQL> SELECT first_name, SOUNDEX(first_name)


2 FROM students;
FIRST NAME
SOUN
Scott
S300
Margaret
M626
Joanne
J500
Manish
M520
Patrick
P362
Timothy
T530
Barbara
B616
David
D130
Ester
E236
Rose
R200
Rita
R300
Shay
SOOO
SELECT first_name
FROM students
WHERE SOUNDEX(first_name) = SOUNDEX('skif );
FIRST NAME
Scott

,


. CHAR, VARCHAR2.
,
NUMBER . :

170

ASCII(sfring)

Oracle?

SQL-

string
. , - ASCII,
7- ASCII. CHR ASCII
. CHR , a ASCII
.
INSTR(sfring/, string2 [,a][,b]) Oracle?
SQL-
string? string/; b
(. ).
INSTRB(sfringf, sfring2 [,a][,b]) Oracle?
SQL-
string2 string/; b
(. ).
INSTRC(sfring/, string? [,a][,b]) OracleS/
SQL-
string? string/; b
Unicode (. ).
INSTR2(sfring/, string? [,a][,b]) OracleQ/

SQL-

string? string/; b
UCS2 (. ).
INSTR4(string/, string? [,a][,b]) OracleQ/

SQL-

string? string?; b
UCS4 (. ).
LENGTH(string)

Oracle?

, (. ).
LENGTHB(string)
Oracle?

SQL-
SQL-

, (. ).
LENGTHC(sfring)

Oracle9/

SQL-

, Unicode (. ).
LENGTH2(sfring)

Oracle9/

SQL-

, UCS2 (. ).
LENGTH4(sfring)

Oracle9/

SQL-

, UCS4 (. ).

INSTR, INSTRB, INSTRC, INSTR2 INSTR4

INSTR(stringl, string2
l, string2 [,a]
INSTRC(stringl, string2 [,a]
INSTR2(stringl, string2 [,a]
lNST~R.4(stringl,string2[,a]

SQL

171

string2
stringl. stringl , .
, stringl .
6- . b 1,
string2 stringl.
string2 , 0. stringl .
INSTR ,
.

INSTR
INSTRB
INSTRC
INSTR2
INSTR4

Unicode
UCS2
UCS4

(_J SELECT INSTRC Scotfs spot , 'of, 1, 2) "First"


FROM dual;
First
11

SELECT INSTRC Scott1 's spot', 'of, -1, 2) "Second"


FROM dual;
Second

SELECT INSTRC Scotfs spot', 'of, 5) "Third"


FROM dual;
Third

11
SELECT INSTRC Scott "s spot', 'of, 12) "Fourth"
FROM dual;
Fourth

LENGTH, LENGTHS, LENGTHC, LENGTH! LENGTH4

LENGTH(rtring)
LENGTHB( siring)
LENGTHC(rfnng)

172

LENGTH4(string)
string. CHAR , CHAR, . string NULL, NULL.
LENGTH -
, .

LENGTH

LENGTHS
LENGTHC

Unicode

LENGTH2

UCS2

LENGTH4

UCS4

SELECT LENGTHC'Mary had a little lamb') "Length"


FROM dual;
Length

22

NLS
NCHR,
.

NLS, . NLS ( Oracle9i Globalization)
Oracle.


CONVERTfsfring, ctesf_
Oracle?
SQL-
charset[,source_charset])
string dest_charset.
source_charset . ,
. CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB NCLOB. VARCHAR2.
dest_charset,
( dest_charset).
NCHR(x)
Oracle9/
SQL-
, ,
. NCHR(x) CHR(x USING NCHAR_CS).

SQL

173


NLS_CHARSET_DECL_LEN(byfe_w/dt, OracleS
SQL-
charset)
( ) NCHAR. byte_width
, a charset ,
.
NLS_CHARSETJD(cnarsef_name)
OracleS
SQL-
charset_name.
'CHAR_CS' charsetjiame ,
a 'NCHAR_CS' .
charsetjiame , NULL.
NLS_CHARSET_ID NLS_CHARSET_NAME- .
NLS_CHARSET_NAME(c/)areef_'D)
OracleS
SQL-
charsetJD. charsetJD
, NULL.
NLS_CHARSET_NAME NLS_CHARSET_ID - .
NLSJNITCAPfsfring [,n/sparams])
Oracle?
SQL-
, ,
. nlsparams ,
. , NLSJNITCAP
, INITCAP. nlsparams 'NLS_SORT=sort', sort
.
NLS , , "Server SQL Reference".
NLS_LOWER(sfrmg [,hlsparams])

Oracle?

SQL-

, . , ,
. nlsparams , NLSJNITCAP. nlsparams
, NLS_LOWER LOWER.
NLS_UPPER(sfring [,n/sparams])
Oracle?
SQL-
, . , ,
. nlsparams , NLSJNITCAP. nlsparams
, NLSJJPPER UPPER.
NLSSORT(string [,n/sparams])

Oracle?

SQL-

, string.
.
nlsparams , NLSJNITCAP. nlsparams ,
.
" "
"Server SQL Reference".
TRANSLATE(sfring USING
OracleS
SQL-
{CHAR_CS|NCHAR_CS})
TRANSLATE ... USING string
( CHAR CS), (
NCHAR_CS). string CHAR, VARCHAR2, NCHAR NVARCHAR2.
CHAR_CS, VARCHAR2, NCHAR_C5
NVARCHAR2. TRANSLATE... USING CONVERT.
, , UCS2 (\),
UNISTR ( Oracle9/ ).

174


UNISTR(s)
OracleS/
SQL-
s, Unicode . s
escape- UCS2, (\),
. ,
, (\\). UNISTR
TRANSLATE...USING , Unicode
escape-.


NUMBER NUMBER. 36 . ACOS,
ASIN, ATAN ATAN2 30 . :

ABS(x)

Oracle?

SQL-

.
ACOSfx)
Oracle?

SQL-

: -1 1. : 0 ,
.
ASIN(x)
Oracle?
SQL-
. : -1 1. : -/2 /2,
.
ATAN(x)
Oracle?
SQL-
. : -/2 /2, .
ATAN2(x, )
Oracle?
SQL-
, : - .
. ATAN2(x, ) , ATAN(x/y).
BITANDfx, )
Oracle?
SQL-
AND ,
.
&& . , BITOR, UTL_RAW , RAW.
CEIL(x)
Oracle?
SQL-
, .
COS(x)
Oracle?
SQL-
.
COSH(x)
Oracle?
.

SQL-

SQL

()

175


Oracle?


SQL-

( = 2.71828183...).
FLOORfx)
Oracle?
SQL-
, .
LN(x)
Oracle?
SQL-
. 0.
LOG(x, )
Oracle?
SQL-
. ,
0 1, .
MOD(x, )
Oracle?
SQL-
. 0, .
POWER(x, )

Oracle?

SQL-

.
, , .
ROUNDfx [,y])
Oracle?
SQL-
, .
0; .
, . .
SIGN(x)
Oracle?
SQL-
< 0, -1. = 0, 0. > 0, 1.
SIN(x)
Oracle?
SQL-
.
SINH(x)
Oracle?

SQL-

.
SQRT(x)
Oracle?

SQL-

. .
TAN(x)
Oracle?
SQL-
.
TANH(x)
Oracle?

SQL-

.
TRUNC(x [,y])
Oracle?
SQL-
, ( ) .
0; . ,
.
WIDTH_BUCKET(x, , max,
Oracle9/
SQL
num_buckets)
.

176

WIDTH_BUCKET

WIDTH_BUCKET(x, mm, max, num_lmckets)


WIDTH_BUCKET . ...max
num_buckets . , . , 0. max, num_backets+l. , max NULL,
a num_backet . NULL, NULL.

20 , 50
(1000/20):
SELECT number_seats, WIDTH_BUCKET(number_seats, 1, 1000, 20) Bucket
FROM rooms;
NUMBER SEATS
1000
500
50
50
50
10
1000
. 75
50

BUCKETS
21
10
1
1
1
1
21
2


DATE.
MONTHS_BETWEEN,
NUMBER, DATE.
.
.

ADD_MONTHS(d, x)
Oracle?
SQL-
d . .
, d,
-. , - d
. d .
CURRENT_DATE

Oracle9/

SQL-

SQL

177

DATE.
SYSDATE , SYSDATE
.
CURRENTJIMESTAMP
[(precision)]

Oracle9/

SQL-

TiMESTAMP WITH TIMEZONE.


precision (),
; 6.
DBTIMEZONE

OracleQ/

SQL-

. ,
CREATE DATABASE ALTER DATABASE.
EXTRACT({YEAR, MONTH, DAY, OracleB/ DATE,
HOUR, MINUTE, SECOND,
OracleQ/
TIMEZONE HOUR,
TIMEZONE_MINUTE,
TIMEZONE REGION,

SQL-

TIMEZONE_ABBR} FROM

datetime_or_interval)

datetimejirjnterval, DATE, DATETIME INTERVAL


, TIMEZONE DATE. , !9/
"ORA-30076: invalid extract field for extract source".
LAST_DAY(d)

Oracle?

SQL-

, d.
, .
LOCALTIMESTAMP[(prec/s/on)]

OracleG/

SQL-

TIMESTAMP.
precision,
; 6. LOCALTIMESTAMP TIMESTAMP,
CURRENTJIMESTAMP TIMESTAMP WITH TIMEZONE.
MONTHS_BETWEEN(dafe?,
date2)

Oracle?

SQL-

datel date2. datel date2 ,


. ( 31- ).
NEW_TIME(d, zone/, zone?)

Oracle?

SQL-

zone2 zone/,
d. Zone/ zone2 ,
5.1. OracleQ/
v$timezone_names.
NEXT_DAY(d, string)

Oracle?

SQL-

178

string , d. string
. ,
d. .
ROUND(d[,])

Oracle?

SQL-

d , format. ,
ROUND TRUNC, 5.2. ,
'DD', d .
SESSIONTIMEZONE

OracleQ/

SQL-

. ,
, .
( ) , ALTER SESSION.
SYS_EXTRACT_UTC(dafef/me)

Oracleft'

SQL-

UTC ( ,
) datetime,
.
SYSDATE

Oracle?

SQL-

DATE. .
SQL- SYSDATE
.
SYSTIMESTAMP

!9/

SQL-

TIMESTAMP WITH TIMEZONE.


SQL- SYSTIMESTAMP
.
TRUNC(d[, format])

Oracle?

SQL-

d, , format.
, ROUND (. 5.2). format ,
'DD', d .
TZ_OFFSET(f/mezone)

Oracle9/

SQL-

timezone
UTC. timezone (. 5.1
v$timezone_names), '+/-:.
SESSIONTIMEZONE DBTIMEZONE.
'+/-:.
5.1. TIME ZONE

AST
ADT
BST

CST

Atlantic Standard Time ( (-) )


Atlantic Daylight Time ( (-) )
Bering Standard Time ( )
Bering Daylight Time ( )
Central Standard Time ( )

SQL

179

5.1. TIME ZONE ()

CDT
EST
EOT
GMT
HST

MST
MDT
NST
PST

YST
YDT

Central Daylight Time ( )


Eastern Standard Time ( )
Eastern Daylight Time ( )
Greenwich Mean Time ( )
Alaska-Hawaii Standard Time ( )
Alaska-Hawaii Daylight Time ( )
Mountain Standard Time ( )
Mountain Daylight Time ( )
Newfounland Standard Time ( )
Pacific Standard Time ( )
Pacific Daylight Time ( )
Yukon Standard Time ( )
Yukon Daylight Time ( )

5.2. ROUND TRUNC

, SCC

SYYYY, YYYY, YEAR, SYEAR, YYY, YY, Y

( 1 )

IYYY, IYY, IY, I

ISO

(
)

MONTH, MON, MM, RM

( )

WW

IW

, ISO

ODD, DD, J

Day, DY, D

, 12, 24

Ml


(d), (dt), () () 5.3. ,
.

180

5.3.

d1-d2

NUMBER

dt1 - dt2
-12

INTERVAL
INTERVAL
He

dt1 + dt2

He

+12

INTERVAL
DATE

d1-n

DATE

dt1 + //
dff -
/7*
H/n

DATETIME
DATETIME
INTERVAL
INTERVAL

d1 d2.
,
.
df 1 dt2.
II 12.
.
.
.
_ .
/'/ 12.
d1 , ,
DATE.
, ,
/7 , ,
DATE.
, .
dt1 .
df/ .
;/, .
//, .

Oracle.



PL/SQL. PL/SQL , . ,
. ,
, PL/SQL.
:


ASCIISTR(string)
OracleS/
SQL-
, SQL (/).
string ( ), ,
, .
BIN_TO_NUM(num [,num]...)
Oracle9/
SQL

SQL

181



. BIN_TO_NUM
, 0 1. ,
BIN_TO_NUM(1,0,1,1) 11, 11 1011.
BIN_TO_NUM GROUP BY.
CHARTOROWID(sfrmg) '
Oracle?
SQL-
CHAR VARCHAR2, (ROWID)
, . string
, ROWID,
(. 2). CHARTOROWID ROWIDTOCHAR,
COMPOSE(sfrmg)
Oracle9/
SQL
string ( )
Unicode . Unicode
Oracle. string
CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB NCLOB.
DECOMPOSE(sfrmg)
OracleG/
SQL
Unicode, string (
). Unicode
Oracle. string CHAR, VARCHAR2,
NCHAR, NVARCHAR2, CLOB NCLOB.
FROM_TZ(f/mesfamp, timezone) OracleS/
SQL-
TIMESTAMP WITH TIMEZONE, timestamp,
, timezone.
HEXTORAW(sfring)
Oracle?
SQL-
, string, RAW.
string .
RAW. HEXTORAW RAWTOHEX
.
NUMTODSINTERVAL(x, unit)
Oracle9/
SQL-
, , INTERVAL DAY TO SECOND.
unit ( CHAR, VARCHAR2, NCHAR NVARCHAR2)
: 'DAY', 'HOUR', 'MINUTE', 'SECOND'. unit
. 9.
NUMTOYMINTERVAL(x, unit)
Oracle9/
SQL-
, , INTERVAL YEAR TO MONTH.
unit ( CHAR, VARCHAR2, NCHAR NVARCHAR2)
: 'YEAR', 'MONTH'. unit
. 9.
REFTOHEX(refra/ue)
Oracle9/
SQL-
REF.
RAWTOHEX(rawa/ue)
Oracle?
SQL-
RAW ,
. rawvalue .
RAWTOHEX HEXTORAW .
RAWTONHEX(raiwa/ue)
Oracle9/
SQL-

182



RAW ,
. rawalue . RAWTONHEX
RAWTOHEX, ,
NVARCHAR2, VARCHAR2.
ROWIDTOCHAR(rovwcf)
Oracle?
SQL-
ROWID ( )
(
rowid). ROWIDTOCHAR CHARTOROWID
.
ROWIDTONCHAR(rovwd)
Oracle9/
SQL-
ROWID ( )
(
rowid). NCHAR, CHAR.
TO_CHAR
Oracle?
SQL-
(. ).
TO_CLOB(str/ng)
Oracle9/
SQL-
CLOB. string
LOB. NCHAR, .
TO_DATE
Oracle?
SQL-
DATE (. ).
TO_DSINTERVAL(string
Oracle9/
SQL-
[,n/sparams])
sfrmg ( CHAR, VARCHAR2, NCHAR NVARCHAR2)
INTERVAL DAY TO SECOND. nlsparams
NLS_NUMERIC_CHARARCTERS .
TO_LOB(/ong_co/umn)
OracleS/
SELECT
1_1 LOB. LONG
LONG RAW CLOB BLOB .
TO_MULTI_BYTE(sfring)
Oracle?
SQL-
,
. ,
, . string
. TO_MULTI_BYTE TO_SINGLE_BYTE
.
TO_NCHAR
Oracle9/
SQL-
TO_NCHAR , TO_CHAR, ,
,
(. ).
TO_NCLOB(sfring)
Oracle9/
SQL-
string NCLOB. string
LOB. string , ,
.
TO_NUMBER
Oracle?
SQL-

SQL

183



(. ).
TO_SINGLE_BYTE(sfr/ng)
Oracle?
SQL-
string .
, ,
. .
TO_SINGLE_BYTE TO_MULTI_BYTE .
TOJTIMESTAMP
19/
SQL-
TIMESTAMP (. ).
TO_TIMESTAMP_TZ
OracleQ/
SQL-
TIMESTAMP WITH TIMEZONE (. ).
TO_YMINTERVAL(sfr/ng)
Oracle9/
SQL-
string ( CHAR, VARCHAR2, NCHAR NVARCHAR2)
INTERVAL YEAR TO MONTH. TOJMINTERVAL TO.DSINTERVAL
, NLS
YEAR TO MONTH, DAY TO SECOND.

TO_CHAR ( -)

TO_CHAR(d

[,fffrmat[,nlsparams]])

d
VARCHAR2. format (),
. .
, . , TO_CHAR,
5.4. format , , .
nlsparams,
. nlsparams :
'NLS_DATE_LANGUAGE= language'
language . TO_CHAR
"Server SQL Reference".

SELECT TO_CHAR(SYSDATE, 'DD-MON-YY HH24.MI:SS1) "Right Now"

FROM dual;
Right Now
10-AUG-01 15:44:54

184

5.4. -


""
, ,

AD, A.D.
AD
AM, A.M.
Ante Meridiem
, B.C.

, SCC
; SCC
D
(1-7)
DAY'
,
DD ,
(1-31)
DDD
(1366)
DY1

2
( Japanese Imperial,
ROC Official Thai Buddha)
2
( Japanese Imperial,
ROC Official Thai Buddha)
FF2

, 12
(1-12)
24
(0-23)
IW
(1 52, 1 53) ISO
IYY, IY, I
, ISO
IYYY
ISO
J
. 1 4712 .
.
Ml
(0 - 59)
MM
Mecflu(1-12);JAN = 1,DEC = 12
MOM1

MONTH1
,
, P.M.
Post Meridiem
Q
(1 - 4); JAN - MAR = 1
RM
(I XII); JAN = I, DEC = XII
RR

RRRR
; RR , .
SS
(0-59)
SSSSS
(0 86 399). 'J.SSSSS'
.
TZD2

TZN2

2
TZM

SQL

185

5.4. -
()

2

TZR
WW
W
2

X
Y.YYY
1
YEAR, SYEAR
YYYY, SYYYY
YYY, YY, Y

( 'US/Pacific')
(1 53). 1
. ,
.
(1 5). ,
WW.


. SYEAR .
. SYYYY
.
,

. , 'MON' 'JAM', '' 'Jan'.


Oracle9i.

TO_CHAR ()

TO_CHAR(

[,format[,nlsparams]])

num NUMBER VARCHAR2.


format .
5.5. , format , ,
num. nlsparams
,
. :
'NLS_NUMERIC_CHARS=" rfg" NLS_CURRENCY=" string"
d g .
siring . , (.),
(,), ($). "Oracle Globalizartion".

FJ SELECT TO_CHAR(123456, '99G99G99') "Result"


FROM dual;
Result
12,34,56

186

SELECT TO_CHAR(123456, 'L99G99D99',


NLS_NUMERIC_CHARACTERS = " , . "
NLS_CURRENCY = "Money" ' ) "Result 2"
FROM dual;
Result 2
Money12,34.56

5.5.

$999

999

Ml

999MI

S9999

9999S

PR

99PR

99D9

9G999

99

L
,

L999
999,999
99.99

99V999

RM

9.99
RM


.
.
,
.
,
.
.
'+' '-'
.
'+'
'-' .
<

.

.
.
. G
.
ISO- .
.
.

.

.
, 10",
V.
.
.
,
.

SQL

187

5.5. ()

rm

rm

FM

FM90.99

0999
9990
99

0
9

,
.

.
, .
, .
.
,
,
. .

TO_DATE

TO_DA.TE(string[,format[,nlsparams]

])

string CHAR VARCHAR2


DATE. format (. 5.4).
format , .
nlsparams TO_DATE , TO_CHAR.
TOJDATE TO_CHAR .

DECLARE
v_CurrentDate DATE;
BEGIN
v_CurrentDate := TO_DATE('January 7, 1973', 'Month DD, Y Y Y V ) ;
END;

TO_NUMBER

TO_NUMBER( string [ ,format[, nlsparams] ])


string CHAR VARCHAR2 NUMBER. format,
. nlsparams ,
TO_CHAR. TO_NUMBER TO_CHAR
.

DECLARE
v Mum NUMBER;

188

BEGIN
v_Num := TO_NUMBER('$12345.67', ' $ 9 9 9 9 9 . 9 9 ' ) ;
END;

OracleQ/

TOJTIMESTAMP TO_TIMESTAMP_TZ

[,format[,nlsparams]])
TO_TIMESTAMP_TZ(string [,farmat[, nbparams] ])
string CHAR VARCHAR2
TIMESTAMP TIMESTAMP WITH TIMEZONE. format (. 5.4). /^ , . nlsparams
TOJTIMESTAMP TO_TTMESTAMP_TZ , TO_CHAR.
SQL-

DECLARE
v_CurrentDate TIMESTAMP;
BEGIN
v_CurrentDate := TO_TIMESTAMP('January 7, 1973', 'Month DD, Y Y Y Y ' ) ;
END;


,
. , . , COUNT , ,
WHERE SELECT. GROUP
BY HAVING.
() : DISTINCT ( ) ALL
(). DISTINCT, , .
ALL, ,
. , ALL ,
.
fOra
OracleQ/

OracleQ i OVER, , .
OVER , .
, , . OVER . "SQL Reference".

SQL

_1J39


AVG([DISTINCT|ALL] col}
Oracle?
.
CORR(x7, x2)
Oracle
, 1
2. , xl 2 NULL,
COVAR_POP(x7, x2)/(STDDEV_POP(x7)*STDDEV_POP(x2)).
COUNT(*|[DISTINCT|ALL] /)
Oracle?
. *, .
, , NULL.
COVAR_POP(x7,x2)
Oracle
, 1
2. (SUM(x/*x2)- SUM(x2)*SUM(x7)/n)/n,
, NULL
COVAR_SAMP(x1, 2)
Oracle
, 1 2.
, 1 2 NULL,
(SUM(x1*x2)-SUM(x1)*SUM(x2)/n)/(n-1), , NULL
CUME_DIST
Oracle
(. "SQL Reference").
DENSE_RANK
Oracle
,
, 1 (. "SQL Reference").
GROUPJDQ
Oracle
,
GROUP BY.
GROUPING
Oracle
(. "SQL Reference").
GROUPINGJD
Oracle
, GROUPING (. "SQL
Reference").
MAX([DISTINCT | All] col)
Oracle?
. ,
DISTINCT ALL ,
.
MIN([DISTINCT | ALL] col)
Oracle?
. ,
DISTINCT ALL ,
.
PERCENTILE.CONT
Oracle
,
(. "SQL Reference").

190


PERCENTILE_DISC
Oracle9/
,
(. "SQL Reference").
PERCENTRANK
OracleQ/
0 1 (. "SQL Reference").
RANK
Oracle9/
. ,
(. "SQL Reference").
REGR
Oracle9/
(REGR_SLOPE, REGRJNTERCEPT, REGR.COUNT, REGR_R2, REGR_AVGX,
REGR.AVGY, REGR_SXX, REGR_SYY REGR_SXY)
. "SQL Reference").
STDDEV([DISTINCT | ALL] col)
Oracle?
.
.
STDDEV_POP(co/)
OracleQ/

.
STDDEV_SAMP(co/)
OracleQ/

.
SUM([DISTINCT | ALL] /)
Oracle?
.
VAR_POP(x)
OracleQ/
NULL.
(2) - SUM(x2)/COUNT(x))/COUNT(x).
VAR_SAMP(x)
OracleQ/
NULL.
(SUMfx2) - SUM(x2)/COUNT(x))/(COUNT(x) - 1).
VARIANCE([DISTINCT | ALL] col)
Oracle?
col.


,
.

BFILENAME(d/rectory, filename)


OracleS


SQL-

BFILE, fi/ejiame
. directory DIRECTORY .

SQL

191

COALESCE(expr7, ..., [])


OracleQ/
SQL-
, NULL, .
NULL, COALESCE NULL. NVL
DECODE(base_expr,
compare/, valuel,
compare?, value2,

Oracle?

^,

~ ..

default)
DECODE IF-THEN-ELSE.
basejsxpr compare/,
compare? .. /'- , /-
(value/). ,
(default). .
, .
NULL-,
NULL. , ,
.
.
DUMP
Oracle?
SQL
.
EMPTY_CLOB/EMPTY_BLOB

OracleS

SQL-

LOB. EMPTY_CLOB ,
PTY_BLOB .
EXISTNODEfXM/Jypejnsfance,
Xpaf/i_sfring)

Oracle9/

SQL

, - XML,
XMLTypejnstance Xpathjtring.
NUMBER, 0, , 0
. XML Oracle.
EXTRACT(XM/Type_/nsfarice,
Oracle9/
SQL
Xpafn_sfr/ng)
XML, XMLTypejnstance
Xpathjtring. XML Oracle.
GREATEST(expr/ [, expr2]...)

Oracle?

SQL-

.
exprl. / ,
, VARCHAR2,
LEAST(expr7 [, expr2]...)
Oracle?
SQL-
. LEAST
GREATEST , .
.
NULLIF(a, )
OracleQ/
SQL
NULL, , , .

192

NVL(expr7, expr2)

Oracle?

SQL-

2, ! NULL-; 1.
1 , ,
exprl. VARCHAR2.
NULL- .
NVL2(expr7, 2, )
OracleQ/
SQL-
/ NULL, 2, .
2, 2 ;
VARCHAR2.
SYS_CONNECT_BY_PATH
Oracle9/
SELECT
SYS_CONNECT_BY_PATH .
(. "SQL Reference").
SYS_CONTEXT(namespace,
OracleS/
SQL-
parameter\,length])
parameter, namespace.
DBMS_SESSION.SET_CONTEXT.
VARCHAR2 256 ,
length, .
SYS_DBURIGEN
OracleQ/
SQL
URL XML .
XML Oracle.
SYS_GUID
OracleS/
SQL-
16- RAW.
SYSJYPEID(objectJype)
Oracle9/
SQL-
ID objectjype.
SYS_XMLAGG
Oracle9/
SQL-
XML .
XML Oracle.
SYS_XMLGEN
Oracle9i
SQL-
XML .
XML Oracle.
TREAT(expr ASfREF] [schema.jtype)
Oracle9i
SQL
TREAT .
. ,
schema.type (REF) ( , ).
UID
Oracle?
SQL-
, .
DID .
USER
Oracle?
SQL-
VARCHAR2, Oracle.
USER .

SQL

USERENV(napaMerp)

193


Oracle?


SQL-

.
VSIZE(x)
OracleQ/
.

SQL-

DUMP

DUMP(expr [,number_format[,start_position] [,length] ]])


VARCHAR2, . number_farmat
:
number format
8
10
16
17

number_format , . start_position length, length ,


start_position. .
,
:

1
2
8
12
23
24
69
96
112
113
114
180
181
182
183
208
231


VARCHAR2
NUMBER
LONG
DATE
RAW
LONG RAW
ROWID
CHAR
GLOB
. BLOB
BFILE
TIMESTAMP
TIMESTAMP WITH TIMEZONE
INTERVAL YEAR TO MONTH
INTERVAL DAY TO SECOND
UROWID
TIMESTAMP WITH LOCAL TIMEZONE


Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
OracleS
OracleS
OracleS
Oracle9/
Oracle9/
Oracle9/
Oracle9/
OracleS/
Oracle9/

194

SELECT first_name, DUMP(first_name) "Dump"


FROM students
FIRST_NAME

Dump

Scott
Margaret
Joanne
Manish
Patrick
Timothy

Typ=1
Typ=1
Typ=1
Typ=1
Typ=1
Typ=1

Len=5: 83 , 99, 111, 116 , 116


Len=8: 77 , 97, 114, 103 , 97, 114, 101, 116
Len=6: 74 , 111, 97, 110 , 110, 101
Len=6: 77 , 97, 110, 105 , 115, 104
Len=7: 80 , 97, 116, 114 , 105, 99, 107
Len=7: 84, 105, 109, 111 , 116, 104, 121

SELECT first_name, DUMP(first_name , 17) "Dump")


FROM students
FIRST_NAME
Dump
Scott
Margaret
Joanne
Manish
Patrick
Timothy

Typ=1 Len=5: S, C, 0, t, t
Typ=1 Len=8: M, a, r, g, a , r, e, t
Typ=1 Len=6: J, o, a, n, n, e
Typ=1 Len=6: M, a, n, i, s , h
Typ=1 Len=7: P, a, t, r, i , c, k
Typ=1 Len=7: T, i, m, 0, t, h,

SELECT first_name, DUMP(first_name , 17, 2, 4) "Dump"


FROM students;
FIRST_NAME
Dump
Scott
Margaret
Joanne
Manish
Patrick
ISERENV

Typ=1
Typ=1
Typ=1
Typ=1
Typ=1

Len=5: c, 0, t, t
Len=8: a, r, 9, a
Len=6: 0, a, n, ii
Len=6: a. n, i, s
Len=7: a, t, r, i

USERENV(optian)
VARCHAR2,
, option.
:

'OSDBA'

'LABEL'

USERENV(option)
OSDBA,
TRUE', 'FALSE'. ,
VARCHAR2, BOOLEAN.
Trusted Oracle.
. "Trusted
Oracle? Server Administrator's Guide".

195

SQL

USERENV(option)

'LANGUAGE'

,
, .
NLS.
languagejerritory.characterset.

'TERMINAL'


. SQL
.

'SESSIONID'

,
AUDITJRAIL TRUE. USERENV('SESSIONID')
SQL.

'ENTRYID'

,
AUDITJRAIL TRUE.
USERENV('ENTRYID')
SQL.

'LANG1'

ISO .
USERENV('LANGUAGE').

*USERENV('LANG') OracleS .

SELECT USERENVC'TERMINAL'), USERENV('LANGUAGE')


FROM dual;
USERENV( USERENV('LANGUAGE')
Windows AMERICAN AMERICA.WE8IS08859P1


. , .

198

4 5 SQL- PL/SQL.

SQL-. , SQL-. , ,
.


SQL- Oracle , (context area). ,
, : , , (active set), ..
, .
(cursor) .
PL/SQL . PL/SQL,
.
.
| CursorLoop.sql
DECLARE
/* */
v_StudentID
students.id%TYPE;
v_FirstName
students.first_name%TYPE;
v_LastName
students.last_name%TYPE;
/* , */
v_Major
students.major%TYPE := 'Computer Science';
/* */
CURSOR c_Students IS
SELECT id, first_name, last_name
FROM students
WHERE major = v_Major;
BEGIN
/*
*/
OPEN c_Students;
LOOP
/* PL/SQL */
FETCH c_Students INTO v_StudentID, v_FirstName, v_LastName;
/* , , , */
EXIT WHEN c_Students%NOTFOUND;
END LOOP;

199

/* , */
CLOSE c_Students;
END;

(explicit) .
SELECT CURSOR...IS.
SQL- (implicit) .
(. ). PL/SQL .


PL/SQL
:
1. .
2. .
3. PL/SQL.
4. .
, .
.


SELECT. :
CURSOR _ IS onepamop_SELECT
_ , a onepamopJSELECT ,
. , ,
PL/SQL (. 3).
PL/SQL, ,
.
SELECT, (join) ,
UNION () MINUS ().

- INTO SELECT,
FETCH.

PL/SQL, .
, .
, :

200

3 DECLARE
v_Department
classes.department%TYPE;
v_Course
classes.course%TYPE;
CURSOR c_Classes IS
SELECT * FROM classes
WHERE department = v_Department;
AND course = v_Course;

,
v_Department v_Course :
)

DECLARE
CURSOR c_Classes IS
SELECT * FROM classes
WHERE department = v_Department;
AND course = v_Course;
v_Department
classes.department%TYPE;
v_Course
classes.course%TYPE;

, ,
, ,
.
. ,
, %ROWTYPE ( , ).
, .


:
OPEN _;
_ .
, :
.
,
, .
.
. PL/SQL:
!_]

DECLARE

v_RoomID
classes.room_id%TYPE;
v_Building
rooms. building%TYPE;
v_Department
classes. department%TYPE;
v_Course
classes. course%TYPE;
CURSOR c_Buildings IS
SELECT building
FROM rooms, classes

201

WHERE rooms.room_id = classes. room_id


and department = v_Department
and course = v_Course;
BEGIN
-
- .
v_Department := 'HIS';
v_Course := 101;
- .
OPEN c_Buildings;
- .
- , .
v_0epartment := 'XXX';
v_Course := -1;
END;

c_Building v_0epartment v_Course


'HIS1 101. . v_Department v_Course ,
. , . (. 4) ,
OPEN,
.
, , .
, .. , ,
. , ('Building Seven'). (), FROM , WHERE,
, , .
.
, .
. OPEN , Oracle ORA-6511,
:
Q AlreadyOpen.sql
SQL> DECLARE
2
v_StudentID students.ID%TYPE;
3

4
5
6
7
8

CURSOR c_A118tudentIDs IS
SELECT ID FROM students;
BEGIN
OPEN c_AHStudentIDs;

- . ORA-6511.

10
OPEN c_AHStudentIDs;
11 END;
12 /

202

DECLARE
ik

ERROR at line 1:
ORA-06511: PL/SQL: cursor already open
ORA-06512: at line 5
ORA-06512: at line 10


INTO FETCH. FETCH :
FETCH _ INTO _;
FETCH ._ INTO aanucbJPL/SQL;
_ , _ PL/SQL, , a 3anucb_PL/SQL
PL/SQL. () INTO , .
c_Buildings, FETCH :
] FETCH c_Buildings INTO v_Building;
, , FETCH:
| BadFetch.sql
DECLARE

v_Department
classes.department%TYPE;
v_Course
classes.course%TYPE;
CURSOR c_AHClasses IS
SELECT *
FROM classes;
v_ClassesRecord c_AllClasses%ROWTYPE;
BEGIN
OPEN c_AHClasses;
- FETCH,
- PL/SQL, .
FETCH c_AHClasses INTO v_ClassesRecord;
- FETCH ,
- 7 classes,
- 2 .
- "PLS-394: wrong number
- of values in the INTO list of a FETCH statement"
- (" INTO FETCH")
FETCH c_AllClasses INTO v_Department, v_Course;
END;

203

FETCH . , FETCH
, .
%NOTFOUND. FETCH
, ..
.

FETCH
. Oracleffi
, BULK
COLLECT (. 12).


, .
PL/SQL, . , ,
, .
:
CLOSE _;
_ . . ,
Oracle :
Q ORA-1001: Invalid Cursor
( )

Q ORA-1002: Fetch out of Sequence


( )

ORA-1001.


PL/SQL ,
.
PL/SQL, %TYPE %ROWTYPE. , ,
. %FOUND, %NOTFOUND,
%ISOPEN %ROWCOUNT. , . 6.1. (OracleSi %BULK_ROWCOUNT, .
. 12.) , temp_table
:

204

num_col

char_col

10
20

'Hello'
There'

%FOUND . TRUE, FETCH , FALSE


. , %FOUND
ORA-1001 ( ). %FOUND ; , . 6.1.

c_TempData%FOUND
: ORA-1001
NULL

TRUE
TRUE
FALSE
: ORA-1001

c_TempData ,
.
c_TempData ,
.
.
FETCH
temp_table.
FETCH
temp_table.
FETCH
, .
c_TempData ,
.

DECLARE
-
CURSOR cJempData IS
SELECT * from tempjable;
--
vJempRecord c_TempData%ROWTYPE;

OPEN c_TempData;

c_TempData INTO v_TempRecord; -


j^>
cJTempData INTO v_TempRecord; -
FETCH cJTempData INTO v_TempRecord; -
CLOSE cJempData;
END;

. 6.1. ,

205

%NOTFOUND %FOUND: %NOTFOUND .


%NOTFOUND TRUE, . .
%NOTFOUND (. . 6.1).

c_TempDataXNOTFOUND
1

: ORA-1001

c_TempOata ,
.

NULL

c_TempData ,
.
.

FALSE

FETCH
temp_table.

FALSE

FETCH
temp_table.

TRUE

FETCH
, .

: ORA-1001

c_TempData ,
.

%ISOPEN , . , %ISOPEN
TRUE, FALSE. %ISOPEN :

c_TempDataJ(lSOPEN

FALSE

c_TempData .

TRUE

c_TempData .

TRUE

c_TempOata .

TRUE

c_TempData .

TRUE

c_TempData .

FALSE

c_TempData .

%ROWCOUNT , . %ROWCOUNT ,
,
ORA-1001. %ROWCOUNT
:

206

c_TempDataXROWCOUNT

ORA- 1001

4
5

2
2

ORA- 1001

c_TempData ,
.
c_TempData ,
.
temp_table.
temp_table.

temp_table.
c_TempData ,
.

. 6.1
.
6.1. ,

c_TempDataX
FOUND

c_TempDataX
NOTFOUND

cJTempDataX
ISOPEN

c_TempDataX
ROWCOUNT

1
2
3

ORA-1001
NULL
TRUE
TRUE
FALSE
ORA-1001

ORA-1001
NULL
FALSE
FALSE
TRUE
ORA-1001

FALSE
TRUE
TRUE
TRUE
TRUE
FALSE

ORA-1001
0
1
2
2
ORA-1001

4
5
6


. (parameterized) ,
(. 9 10), . c_Classes:

[_| - Parameterized.sql
DECLARE
v_Department
classes. department%TYPE;
v_Course
classes.rse%TYPE;
CURSOR c_Classes IS
SELECT
FROM classes
WHERE department = v_Department
AND course = v_Course;
c_Classes v_Department
v_Course. c_Classes :

207

rj - Parameterized.sql
DECLARE
CURSOR c_Classes (p_Department classes.departnentXTYPE,
p_Course classes. courseJSTYPE) IS
SELECT *

FROM classes
WHERE department = p_Department
AND course = p_Course;


OPEN, :
FJ -- Parameterized, sql
OPEN c_Classes('HIS', 101);
'HIS' p_Department, a 101 p_Course. , .
9.


,
SELECT,
. SQL , . SQL- .
, SQL- . PL/SQL SQL-, SQL-
.
INSERT,
UPDATE, DELETE, SELECT...INTO.
SQL- PL/SQL,
OPEN, FETCH CLOSE . SQL- . , , INSERT ,
UPDATE .
Q NoMatch.sql
BEGIN
UPDATE rooms
SET number_seats = 100
WHERE room_id = 99980;
- UPDATE
, rooms.
IF SQLXNOTFOUND THEN
INSERT INTO rooms (room_id, number_seats)
VALUES (99980, 100);
END IF;
END;

208

SQL%ROWCOUNT:
rj

NoMatch.sql
BEGIN

UPDATE rooms
SET number_seats = 100
WHERE room_id = 99980;
- UPDATE
- , rooms.
IF SQLXROWCOUNT = THEN
INSERT INTO rooms (room_id, number_seats)
VALUES (99980, 100);
END IF;
END;
SQL%NOTFOUND
SELECT...INTO, . , SELECT...INTO , Oracle :
FJ ORA-1403: no data found
( )


, SQL%NOTFOUND .
SOJL*Plus:
Q - NoDataFound.sql
SQL> DECLARE
2
- .
3
v_RoomData rooms%ROWTYPE;
4 BEGIN

- -1.
6
SELECT *
7
INTO vJtoomData
8 .
FROM rooms

9
10
11
12
13
14
15

WHERE room_id = -1;


- ,
- .
IF SQL%NOTFOUND THEN
DBMSJUTPUT. PUT_LINECSQL%NOTFOUND is true! ');
END IF;

16 EXCEPTION
17
WHEN NO_DATA_FOUND THEN
18
DBMSJJUTPUT.PUT_LINE('NO_DATA_FOUND raised!');
19 END;
20 /

NO DATA FOUND raised!


PL/SQL procedure successfully completed.

209

7.
, SQL%NOTFOUND
NO_DATA_FOUND, .
SQL%ISOPEN,
FALSE, .



. (fetch loop) , , .
.



(LOOP...END LOOP).
. :
Q - Si.mpleLoop.sql
DECLARE
- ,
- .
v_StudentID
students.id%TYPE;
v_FirstName
students. first_name%TYPE;
v_LastName
students.last_name%TYPE;
- -
CURSOR c_HistoryStudents IS
SELECT id, first_name, last_name
FROM students
WHERE major = 'History';
BEGIN
- .
OPEN c_HistoryStudents;
LOOP

- .

FETCH c_HistoryStudents INTO v_StudentID, v_FirstName, v_LastName;


-- , .
EXIT WHEN c_HistoryStudentsXNOTFOUND;
- .
- History 301,
- registered_students. ,
- temp_table.
INSERT INTO registered_students (student_id, department, course)

210

VALUES (v_StudentID, 'HIS', 301);

.
INSERT INTO temp_table (num_col, char_col)
VALUES (v_StudentID, v_FirstName || ' ' II v_LastName);
END LOOP;

- , .
CLOSE c_HistoryStudents;
END;

, EXIT WHEN
FETCH. c_HistoryStudents
%NOTFOUND .
, EXIT WHEN . , NULL.
, , EXIT
WHEN :
- ExitWhen.sql
DECLARE

- ,
- .
v_StudentID students.id%TYPE;
v_FirstName students.first_name%TYPE;
v_LastName students.last_name%TYPE;
- -
CURSOR c_HistoryStudents IS
SELECT id, first_name, last_name
FROM students
WHERE major = 'History';
BEGIN
- .
OPEN c_HistoryStudents;
LOOP
- .
FETCH c_HistoryStudents INTO v_StudentID, v_FirstName, v_LastName;
-. .
- History 301,
- registered_students. ,
- temp_table.
INSERT INTO registered_students (student_id, department, course)
VALUES (v_Student!D, 'HIS', 301);
INSERT INTO temp_table (num_col, char_col)
VALUES (v_StudentID, v_FirstName || ' ' II v_LastName);
- , .
EXIT WHEN c_HistoryStudentsXNOTFOUND;
END LOOP;

211

- , .
CLOSE c_HistoryStudents;
END;

v_StudentID, v FirstName v_LastName ,


. ,
, . - ,
registered_students tempjtable,
, .

WHILE
WHILE...LOOP. :
- WhileLoop.sql
DECLARE
- -
CURSOR c_HistoryStudents IS
SELECT id, first_name, last_name
FROM students
WHERE major = 'History';
- .
v_StudentData c_HistoryStudents%ROWTYPE;
BEGIN
- .
OPEN c_HistoryStudents;
- , WHILE.
FETCH c_HistoryStudents INTO v_StudentData;
- , .
WHILE cJistoryStudentsXFOUND LOOP
- .
- History 301,
- registered_students, ,
- temp_table.
INSERT INTO registered_students (student_id, department, course)
VALUES (v_StudentData. ID, 'HIS', 301);
INSERT INTO temp_table (num_col, char_col)
VALUES (v_StudentData.ID,
v_StudentData.first_name 1 1 ' ' 1 1 v_StudentData.last_name);
- . %FOUND
- , .
FETCH c_HistoryStudents INTO v_StudentData;
END LOOP;
- , .

212

CLOSE c_HistoryStudents;
END;

, LOOP...END
LOOP (. ). , FETCH
.
c_HistoryStudents%FOUND
.

FOR
, ,
OPEN, FETCH CLOSE.
PL/SQL FOR, . :

ForLoop.sql
DECLARE

- -.
CURSOR c_HistoryStudents IS
SELECT id, first_name, last_name
FROM students
WHERE major = 'History';

BEGIN
- .
- c_HistoryStudents.
FOR v_StudentData IN c_HistoryStudents LOOP
- .
- .
- History 301,
- registered_students. ,
- temp_table.
INSERT INTO registered_students (student_id, department, course)
VALUES (v_StudentData.ID, 'HIS', 301);
INSERT INTO temp_table (num_col, char_col)
VALUES (v_StudentData.ID,
v_StudentData.first_name | ' ' I I v_StudentOata.last_name);
END LOOP;

END;

-
- c_HistoryStudents.

, . -, v_StudentOata
. PL/SQL, FOR. c_HistoryStudents%ROWTYPE, FOR.

213

, FOR (. 3). -
FOR.
-, c_HistoryStudents , . , . %FOUND
.
, .
FOR , ,
,
, .
FOR
FOR . , :

] - ImplicitFOR.sql
BEGIN
-- . OPEN.
FOR v_StudentData IN (SELECT id, first_name, last_name,
FROM students
WHERE major = 'History') LOOP
- FETCH %NOTFOUND.
- .
- History 301, registered_students.
- , temp_table.
INSERT INTO registered_students (student_id, department, course)
VALUES (v_StudentData,ID, 'HIS', 301);
INSERT INTO temp_table (num_col, char_col)
VALUES (v_StudentData.ID,
v_StudentData.first_name 1 1 ' ' 1 1 v_StudentData.last_name);
END LOOP;
- , , CLOSE.
END;

FOR..
v_StudentData .
.

NO_DATA_FOUND %NOTFOUND
NO_DATA_FOUND ( ) SELECT...INTO,
WHERE .
%NOTFOUND TRUE.
WHERE UPDATE DELETE, SQJL%NOTFOUND
TRUE. , ,
NO_DATA_FOUND, %NOTFOUND
%FOUND.

214

SELECT FOR UPDATE



, . PL/SQL , : FOR UPDATE
( ), ,
WHERE CURRENT OF ( ...) UPDATE
DELETE.

FOR UPDATE
FOR UPDATE SELECT. ,
ORDER BY ( ):
SELECT ... FROM ... FOR UPDATE [OF 1__] [NOWAIT]
/1__, ,
. . ,
, . SELECT...FOR UPDATE.
] DECLARE
- FOR UPDATE .
CURSOR cJUlStudentds IS
.SELECT *
FROM students
FOR UPDATE OF first_name, last_name;
- .
CURSOR c_LargeClasses IS
SELECT department, course
FROM classes
WHERE max_students > 50
FOR UPDATE;

SELECT , , . ,
, .
. , , Oracle (snapshot) . ,
, . ,
, , .
, , . .
FOR UPDATE
.
.

215

,
SELECT...FOR UPDATE . NOWAIT ( ), OPEN ,
:
[_) ORA-54: resource busy and acquire with NOWAIT specified
( NOWAIT)

, .
19
SELECT...FROM...FOR UPDATE [OF __] [WAIT n]
.
, ORA-54.
WHERE CURRENT OF
FOR UPDATE, UPDATE
SELECT WHERE CURRENT OF.
:
WHERE CURRENT OF
, FOR UPDATE.
WHERE CURRENT OF , . ,
, HIS 101.
j -- Forllpdate.sql
DECLARE

- ,
- .
v_NumCredits classes.num_credits%TYPE;
- ,
- HIS 101.
CURSOR c_RegisteredStudents IS
SELECT *
FROM students
WHERE id IN (SELECT student_id
FROM registered_students
WHERE department= 'HIS'
AND course = 101)
FOR UPDATE OF current_credits;
BEGIN
- .
FOR v_Student!nfo IN c_RegisteredStudents LOOP
- HIS 101.
SELECT num credits

216

INTO v_NumCredits
FROM classes
WHERE department = 'HIS' .
AND course = 101;
- , .
UPDATE students
SET current_credits = current_credits + v_NumCredits
WHERE CURRENT OF cJtegisteredStudents;
END LOOP;
- .
COMMIT;
END;

UPDATE ,
FOR UPDATE .
, .
FOR UPDATE, , WHERE CURRENT
OF.
( ). UPDATE DELETE, ,
, , .
WHERE CURRENT , FOR UPDATE.

COMMIT
, COMMIT . , , . FOR
UPDATE , COMMIT .
, Oracle:
ORA-1002: fetch out of sequence
( )

,
.
commit.sql
DECLARE
,
- ,

CURSOR c_AHStudents IS
SELECT *
FROM students
FOR UPDATE;
-

217

v_StudentInfo c_AUStudents%ROWTYPE;
BEGIN
- . .
OPEN c_AHStudents;
- .
FETCH c_A118tudents INTO v_Student!nfo;
- COMMIT.
- .
COMMIT;
- FETCH ORA-1002.
FETCH c_AHStudents INTO v_StudentInfo;
END;
, COMMIT SELECT...FOR UPDATE, COMMIT
. COMMIT
. SELECT...FOR UPDATE, .

*^^*^^

SELECT...FOR UPDATE,
COMMIT .
, ,
"-1555 snapshot too old"
( ).

, ,
, COMMIT ? WHERE CURRENT OF ,
FOR UPDATE. WHERE UPDATE,
:
Q commit.sql
DECLARE
- ,
- .
v_NumCredits classes.num_credits%TYPE;
- ,
- HIS 101.
CURSOR c_RegisteredStudents IS
SELECT *
FROM students
WHERE id IN (SELECT student_id
FROM registered_students
WHERE department= 'HIS'
!
AND course = 101);

218

BEGIN

- .
FOR v_Student!nfo IN c_RegisteredStudents LOOP
- HIS 101.
SELECT num_credits
INTO v_NumCredits
FROM classes
WHERE department = 'HIS'
AND course = 101;
- , .
UPDATE students
SET current_credits = current_credits + v_NumCredits
WHERE id = v.Studentlnfo.id;

- ,
- FOR UPDATE.
COMMIT;
END LOOP;
END;
, , WHERE
CURRENT OF, .
, , , .


, ROWID.
ROWID PL/SQL
( ROWID UROWID)
WHERE WHERE rowid = v_RowID.



(static cursors), SQL-,
.
(cursor variable)
. PL/SQL, . PL/SQL,
.

SQL
(. 12).

219

, . ,
REF. , ,
.
,
.
. 9 10.


. OracleS . (OracleS REF ; . 12.) 3,
, . . ,
, . PL/SQL :

REF
. REF
, .
, REF CURSOR. :
TYPE _ IS REF CURSOR [RETURN _];
_ , _
, ,
.
, , .
%ROWTYPE.
. .

| RefCursors.sql
DECLARE
- %ROWTYPE
TYPE t_StudentsRef IS'REF CURSOR
RETURN students%ROWTYPE;
- ,
TYPE t_NameRecord IS RECORD (
first_name students.first_name%TYPE,
last_name students. last_name%TYPE);
-
v_NameRecord t_NameRecord;

220

6
-- , .
TYPE t_NamesRef IS REF CURSOR
RETURN t_NameRecord;
- %TYPE .
TYPE t_NamesRef2 IS REF CURSOR
RETURN t_NameRecord%TYPE;
- , .
v_StudentCV t_StudefitsRef;
v_NameCV
t_NamesRef;


, , (constrained):
. , , .
ROWTYPE_MISMATCH ( ).
PL/SQL (unconstrained)
, RETURN .
. , .
| - RefCursors.sql
DECLARE

-
TYPE t_FlexibleRef IS REF CURSOR;
- .
v_CursorVar t._FlexibleRef;


, . ,
: PL/SQL.


.
. , , -.
*.
OCI
JDBC. Oracle.

221

*
*,
SQL_CURSOR. EXEC SQL
ALLOCATE. , * :
Q

SQL_CURSOR v__CursorVar;
EXEC SQL ALLOCATE : v_CursorVar;

,
.


PL/SQL. , .
,
. .


SELECT
OPEN,
:
OPEN _ FOR onepamop_select;

_ ,
a onepamop_sekct . , , . :
rj ORA-6504: PL/SQL: return types of result set variables or query
do not match
(PL/SQL:
)

PL/SQL ,
, 7. :
)

DECLARE
TYPE t_ClassesRef IS REF CURSOR RETURN classes%ROWTYPE;
v_ClassesCV t_ClassesRef;

v_ClassesCV:
]

OPEN v_ClassesCV FOR


SELECT * 'FROM classes;

v_ClassesCV :
] OPEN v_ClassesCV FOR

222

SELECT department, course FROM classes;

ORA-6504, ,
.
OPEN...FOR, , OPEN: .
OPEN...FOR
.
FETCH ( , ), .
\

, OPEN FOR,

. " Oracle8\
SQL (. 12.)


, , CLOSE. , , ,
, , .
.
, , .


*, . PL/SQL,
classes,
rooms, .
.
]

cursor"].
/* S Q L . */
tfinclude <stdio.h>
EXEC SQL INCLUDE SQLCA;
/* */
char *v_Username = "example/example";
/* SQL. */
SQL_CURSOR v_CursorVar;
/* */
int v_Table;
/* rooms */

int

v_RoomID;

VARCHAR v_Description[2001];
/* classes */
VARCHAR v_Department[4];
int v_Course;
/* - */
void handle_error() {
printf("SQL Error occurred!\n");
printf ("%. *s\n", sqlca. sqlerrm. sqlerrml, sqlca. sqlerrm.sqlerrmc);
EXEC SQL ROLLBACK WORK RELEASE;
exit(1);
>
int main() {
/* */
char v_Choice[20];
/* . ,
SQL, handle_error(). */
EXEC SOL WHENEVER SQLERROR DO handle_error();
/* . */
EXEC SQL CONNECT : v_Username;
printf("Connected to Oracle.\n");
/* . */
EXEC SQL ALLOCATE :v_CursorVar;
/* , ,
v_Choice. */
printf("Choose from (C)lasses or (R)ooms. Enter or r: ");
gets(v_Choice);
/* . */
if (v_Choice[0] == '')
v_Table = 1;
else
v_Table = 2;
/* PL/SQL. */
EXEC SQL EXECUTE
BEGIN
IF :v_Table = 1 THEN
/* classes. */
OPEN :v_CursorVar FOR
SELECT department, course
FROM classes;
ELSE
/* rooms. */
OPEN :v_CursorVar FOR
SELECT room_id, description
FROM rooms;

223

224

END IF;
END;
END- EXEC;
/* . */
EXEC SQL WHENEVER NOT FOUND DO BREAK;

/* . */
for (;;) {
if (v_Table == 1) {

/* . */
EXEC SQL FETCH :v_CursorVar
INTO : v_Department, :v_Course;
/* . v_Department
VARCHAR, . len
. . */
printf ("%. *s %d\n", v_Department. len, v_Department.arr,
v_Course);

}
else {
/* . */
EXEC SQL FETCH :v_CursorVar
INTO :v_RoomID, v_Description;
/* . v_Description
VARCHAR, .len
. . */
printf ( "%d %. *s\n", v_RoomID, v_Description. len,
v_Description.arr);

/* . /
EXEC SQL CLOSE : v_CursorVar;

/* . */
EXEC SQL COMMIT WORK RELEASE;

( ) , . ,
. ,
classes, rooms.


,
PL/SQL. ,
classes rooms
.
9 10.

225

cursor2.sql
CREATE OR REPLACE PROCEDURE ShowCursorVariable
/* .
_ -- 'classes', temp_table
classes. p_Table - 'rooms',
rooms. */
(p_Table IN VARCHAR2) AS
/* */
TYPE t_ClassesRooms IS REF CURSOR;
/* . */
v_CursorVar t_ClassesRooms;
/* */
v_Department 'classes.department%TYPE;
v_Course
classes, course%TYPE;
v_RoomID
rooms,room_id%TYPE;
v_Description rooms. description%TYPE;
BEGIN
- .
IF p_Table = 'classes' THEN
OPEN v_CursorVar FOR
SELECT department, course
FROM classes;
ELSIF p_table = 'rooms' THEN
OPEN v_CursorVar FOR
SELECT room_id, description
FROM rooms;
ELSE
/* . */
RAISE_APPLICATION_ERROR (-20000,
'Input must be ''classes' or rooms''');
END IF;
/* . , EXIT WHEN
FETCH. */
LOOP
IF p_Table = 'classes' THEN
FETCH v_CursorVar INTO
v_Department, v_Course;
EXIT WHEN v_CursorVar%NOTFOUND;
INSERT INTO temp_table (num_col, char_col)
VALUES (v_Course, vj)epartment);
ELSE

FETCH v_CursorVar INTO


v_RooraID, v_Description;
EXIT WHEN v_CursorVAR%NOTFOUND;
INSERT INTO temp_table (num_col, char_col)
VALUES (v_RoomID, SUBSTR(v_Description, 1, 60));

226

END IF;
END LOOP;

/* . */
CLOSE v_CursorVar;
COMMIT;
END ShowCursorVariable;



,
,
. :
. ,
.

. PL/SQL (, Oracle
Form), .
PL/SQL ( ,
) . , REF CURSOR. , ,
(, KaKjDBC ResultSets).
SQL
*.
, OPEN...FOR,
FOR UPDATE. OracleSz
.

>

,
SQL-. , , .
, ..
. ,
.
PL/SQL.

228


, . PL/SQL
(exception)
(exception handler). Oracle ,
. ,
.
.


PL/SQL Ada,
. PL/SQL ,
, . PL/SQL Java. , Java
, PL/SQL. ,
Java, PL/SQL .
, PL/SQL, 7.1.
7.1. PL/SQL

PL/SQL

PL/SQL

:
, .
:

.


, . PL/SQL, . ,
. ,
:
) PLS-201: identifier - SSTUDENTS' must be declared
( 'SSTUDENTS' )
SELECT students:

229

DECLARE
v_NumStudents NUMBER;
BEGIN

SELECT COUNT(*)
INTO vJiumStudents
FROM sstudents;
END;

,
. SQL, :
Q ORA-0001; unique constraint violated
( )
, :
] ORA-06502: PL/SQL: numeric or value error
( )

PL/SQL , SQL

SQL PL/SQL
PL/SQL,
,

.
SQL 12.

(raised) .
,
. .
,
(,
), ,
. :

Q int = 1, = 2, z = 3;
f(x)i /* ; . */
if <>
handle_error (...);
= 1 / z;
if <>
handle_error(...);
z = + ;
if <>
handle_error(,..);

230

: . ,
. , ,
, . , , , PL/SQL:
DECLARE

NUMBER := 1;
NUMBER := 2;
z NUMBER := 3;
BEGIN
f(x);

:= 1 / z;
z = x + y;
EXCEPTION
WHEN OTHERS THEN

/* */
handle_error(...);

END;

,
. :
.

, . , , ,
.
, .


,
, . :
().

,
, , , , , Oracle, ,
, .
SQL PL/SQL.
, , PL/SQL. , (EXCEPTION)
. :

231

DECLARE

e_TooManyStudents EXCEPTION;

e_TooManyStudents , .
,
,
. , PL/SQL, 3.

Oracle , Oracle.
(NUMBER, VARCHAR2 ..),
STANDARD (. 3). , ,
, .
7.2.


Oracle (.
" EXCEPTIONJNIT").
7.2.
Oracle

ORA-0001

DUP_VAL_ON_INDEX

ORA-0051

TIMEOUT_ON_RESOURCE

ORA-0061

TRANSACTION_BACKED_OUT1

ORA-1001

INVALID_CURSOR

ORA-1012

NOT_LOGGED_ON

Oracle

ORA-1017

LOGIN_DENIED

ORA-1403

NO_DATA_FOUND

ORA-1410

SYSJNVALID.ROWID2

ORA-1422

TOO_MANY_ROWS

ORA-1476

ZERO_DIVIDE

ORA-1722

INVALID_NUMBER



rowid
SELECT...INTO



NUMBER; "1"

ORA-6500

STORAGE ERROR

PL/SQL; ,
PL/SQL

232

7
7.2.
()
Oracle

ORA-6501

PROGRAM_ERROR

PL/SQL

ORA-6502

VALUE_ERROR

ORA-6504

ROWTYPE_MISMATCH


PL/SQL

ORA-6511

ORA-6530

CURSOR_ALREADY_OPEN
ACCESSJNTO_NUlT

ORA-6531

COLLECTION IS NULL1


PL/SQL,
NULL, ,
EXISTS

ORA-6532

SUBSCRIPT_OUTSIDE_LIMIT1


,
(, -1)

ORA-6533

SUBSCRIPT_BEYOND_COUNT'


, ,

ORA-6592

CASE_NOT_FOUND3


WHEN CASE

ORA-30625

SELF IS NULL2


NULL-


NULL-

!8 .
OracleBi .
Oracle9i .


. "PL/SQL User's Guide".
INVALID_CURSOR
,
. CURSOR_ALREADY_OPEN.
NO_DATA_FOUND
. : SELECT...INTO
. , TOO_MANY_ROWS. :
PL/SQL,
. ,
NO_DATA_FOUND:

233

NoDataFound.sql
SQI_> DECLARE
2
TYPE t_NumberTableType IS TABLE OF NUMBER
3
INDEX BY BINARY_INTEGER;
4
v_NumberTable t_NumberTableType;
5
v_TempVar NUMBER;
6 BEGIN
7
v_TernpVar := v_NumberTable(1);
8 END;

9 /
DECLARE
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 7

PL/SQL 8.
INVALID_NUMBER
SQL- . VALUE_ERROR. ,
INVALID_NUMBER, 'X' :
] INSERT INTO students (id, first_name, lastjiame)
VALUES ( ' X ' , 'SCOTT', 'Smith');

STORAGE_ERROR PROGRAM_ERROR . (STORAGEJERROR), PL/SQL (PROGRAM,


ERROR).
PL/SQL, Oracle (Oracle Technical Support).
VALUE_ERROR , ,
.
SQL-, INVALID_
NUMBER. VALUE_ERROR , SELECT...INTO, RETURNING INTO SQL .
PL/SQL.
, VALUE_ERROR.
OracleS VALUE_ERROR "Numeric
or Value Error" ( ). OracleS . :
[_J

ValueError.sql
SQL> DECLARE
2
v_TempVar VARCHAR2(3);

234

3 BEGIN
4
v_TempVar := ' A B C D ' ;
5 END;

6 /
DECLARE
*

ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 4
SQL> DECLARE

2 v_TempVar NUMBER(2);
3 BEGIN
4
SELECT id
b
INTO v_TempVar
6
FROM students
7
WHERE last_name = 'Smith';
8 END;
9 /
DECLARE
*

ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: number precision too large
ORA-06512: at line 4

ROWTYPE_MISMATCH

PL/SQL. , ROWTYPE_MISMATCH
, , . 6,
.


, , () . , ,
RAISE,
( , Oracle EXCEPTIONJNIT)

Oracle. Oracle,
, . OTHERS (. " OTHERS").
RAISE. , " , ":

235

[_J -- UserDefined.sql
DECLARE

-
eJTooManyStudents EXCEPTION;
- , HIS-101
v_CurrentStudents NUMBER(3);
- , HIS-101
v_MaxStudents NUMBER(3);
BEGIN
/*
. */
SELECT current_students, max_students
INTO v_CurrentStudents, v_MaxStudents
FROM classes
WHERE department = 'HIS' AND course = 101;
/ . /
IF v_CurrentStudents > v_MaxStudents THEN
/* --
. */
RAISE e_TooManyStudents;
ENF IF;

END;


.
, (
), (. "
").
(. . 7.1) .
Oracle. , PL/SQL
DUP_VAL_ON_INDEX:
] - DupValOnlndex.sql
BEGIN
INSERT INTO students (id, first_name, last_name)
VALUES (20000, 'John', 'Smith');
INSERT INTO students (id, first_name, last_name)
VALUES (20000, 'Susan', 'Ryan');
END;
, id students , . INSERT
20000 :
Q ORA-0001: unique constraint (<constraint name>) violated
( )

236

DUP_VAL_ON_
INDEX.

DECLARE
A EXCEPTION;*'
BEGIN

.


.

EXCEPTION
WHEN A THEN


.
.

. 7.1.


. 7.1,

. . ,
. :
EXCEPTION
WHEN __1 THEN
_1;
WHEN __2 THEN
2;
[ WHEN OTHERS THEN
_; ]
END;

WHEN () ,
. WHEN
,
. :

) UserDefined.sql
DECLARE

237

-
e_TooManyStudents EXCEPTION;
- , HIS-101
v_CurrentStudents NUMBER(3);
- HIS-101
v_MaxStudents NUMBER(3);
BEGIN
/*
. */
SELECT current_students, max_students
INTO v_CurrentStudents, v_MaxStudents
FROM classes
WHERE department = 'HIS' AND course = 101;
/* . */
IF v_CurrentStudents > v_MaxStudents THEN
/* --
. */
RAISE e_TooManyStudents;
END IF;
EXCEPTION
WHEN e_TooManyStudents THEN
/* , , HIS-101
. ,
. */
INSERT INTO log_table (info)
VALUES ('History 101 has' | |v_CurrentStudents ||
'students: max allowed is' || v_MaxStudents);
END;
, WHEN,
OR ():
EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
INSERT INTO log_table (info)

VALUES ( ' A select error occu r e d . ' ) ;


END;
I

Java,
,
,
, .
PL/SOL
.

238

. ,
PL/SQL PLS-483,
SQL*Plus:
DuplicateHandlers.sql
SQL> DECLARE
2
-
3
e_Exception1 EXCEPTION;
4
e_Exception2 EXCEPTION;
5 BEGIN

6 - 1
7
RAISE e_Exception1;
8 EXCEPTION
9 WHEN e_Exception2 THEN
10
INSERT INTO log_table (info)
11
VALUES ('Handler 1 executed!');
12 WHEN e_Exception1 THEN
13
INSERT INTO log_table (info)
14
VALUES ('Handler 3 executed!');
15 WHEN e_Exception1 OR e_Exception2 THEN
16
INSERT INTO log_table (info)
17
VALUES ('Handler 4 executed!');
18 END;
19 /
WHEN e_Exception1 OR e_Exception2 THEN
-

ERROR at line 15:


ORA-06550: line 15, column 3:
PLS-00483: exception 'E_EXCEPTION2' may appear in at most one exception
handler in this block
ORA-06550: line 0, column 0:
PL/SQL: Compilation unit analysis terminated
OTHERS
PL/SQL WHEN OTHERS. OTHERS ()
, WHEN,
( Exception Java).
, (
) . WHEN
OTHERS , . OTHERS (
) .
(.
" "). , .

239

OTHERS:
] -- UserDefined.sql
DECLARE
-
e_TooManyStudents EXCEPTION;
- , HIS-101
v_CurrentStudents NUMBER(3);
- HIS-101
v_MaxStudents NUMBER(3);
BEGIN
/*
, */
SELECT current_students, max_students
INTO v_CurrentStudents, v_MaxStudents
FROM classes
WHERE department = 'HIS' AND course = 101;
/* . */
IF v_CurrentStudents > v_MaxStudents THEN
/* --
. */
RAISE e_TooManyStudents;
END IF;
EXCEPTION
WHEN e_TooManyStudents THEN
/* , , HIS-101
. ,
. */
INSERT INTO log_table (info)
VALUES ('History 101 has' || v_CurrentStudents ||
'students: max allowed is' || v_MaxStudents);
WHEN OTHERS THEN
/* , . */
INSERT INTO log_table (info) VALUES ('Another error occurred');
END;
OTHERS , . , , OTHERS,
SQLCODE
SQLERRM (. ).

240

*

WHEN OTHERS THEN NULL;
, ,
'. OTHERS
, ,
.

SQLCODE SQLERRM OTHERS , Oracle . ,


, .
PL/SQL : SQLCODE SQLERRM. SQLCODE ,
a SQLERRM . , , SQLCODE 1, a SQLERRM
"User-defined Exception" ( ).

DBMS_UTILITY.FORMAT_ERROR_STACKTavKe

SQLERRM (. ).

PL/SQL,
OTHERS.

Qj - UserDefined.sql
DECLARE
-
e_TooManyStudents EXCEPTION;

- , HIS-101
v_CurrentStudents NUMBER(3);
- HIS-101
v_MaxStudents NUMBER(3);
-
v_ErrorCode NUMBER;
-
v_ErrorText VARCHAR2(200);
BEGIN
/*
. */
SELECT current_students, max_students
INTO v_CurrentStudents, v_MaxStudents
FROM classes
WHERE department = 'HIS' AND course = 101;
/* . */
IF v_CurrentStudents > v MaxStudents THEN

241

/* --
. */
RAISE e_TooManyStudents;
END IF;
EXCEPTION
WHEN e_TooManyStudents THEN
/* , , HIS-101
. ,
. */
INSERT INTO log_table (info)
VALUES ('History 101 has' | v_CurrentStudents ||
'students: max allowed is' || v_MaxStudents);
WHEN OTHERS THEN
/* , */
v_ErrorCode := SQLCODE;
- SUBSTR
v_ErrorText := SUBSTR(SQLERRM, 1, 200);
INSERT INTO log_table (code, message, info) VALUES
(v_ErrorCode, v_ErrorText, 'Oracle error occurred');
END;
\

Oracle 512 . v_ErrorText 200 (


code logjtable).
200 ,
Q v_ErrorText := SQLERRM;

VALUE_ERROR.
SUBSTR, v _ E r r o r T e x t 200 . SUBSTR PL/SQL
5.
, SQLCODE SQLERRM , SQL-. ,
SQL-.
SQLERRM . , . .
SQLERRM ,
] ORA-0000: normal, successful completion
SQLERRM ,
+100,
Q

non-ORACLE Exception

SQLERRM(IOO)
i_) ORA-1403: no data found

242

SQLCODE , Oracle.
"ORA-1403: no data found", SQLCODE
+100.
SQLERRM
,
f_] ORA-0000: normal, successful completion
A SQLCODE 0.
:
[_)

-- sqlerrm.sql
SQL> BEGIN
2
DBMS_OUTPUT.PUT_LINECSQLERRM(0): ' || SQLERRM(O));
3
DBMS_OUTPUT.PUT_LINECSQLERRM(100): ' | SQLERRM(IOO));
4
DBMS_OUTPUT.PUT_LINE('SQLERRM(10): ' | | SQLERRM(IO));
5
DBMS_OUTPUT.PUT_LINE('SQLERRM: ' || SQLERRM);
6
DBMS_OUTPUT.PUT_LINECSQLERRM(-1): ' | SQLERRM(-1));
7
DBMS_OUTPUT.PUT_LINE( 1 SQLERRM(-54): ' || SQLERRM(-54));
8 END

9 /

SQLERRM(O): ORA-0000: normal, successful completion


SQLERRM(IOO): ORA-01403:'no data found
SQLERRM(IO): -10: non-ORACLE exception
SQLERRM: ORA-0000: normal, successful completion
SQLERRM(-I): ORA-00001: unique constraint (.) violated
SQLERRM(-54): ORA-00054: resource busy and acquire with NOWAIT specified
PL/SQL procedure successfully completed.

SQLERRM
( , SQLCODE).

, ,
-1 (. ).

EXCEPTIONJNIT
Oracle, , OTHERS.
EXCEPTIONJNIT (. 3). EXCEPTIONJNIT
:
PRAGMA EXCEPTIONJNIT (__,11,,
_ _ Oracle);
__ ,
, __01 , .
.

243

, e_MissingNull
,
"ORA-1400: mandatory NOT NULL column missing or
NULL during insert" ( NOT NULL
NULL-).
Q - Exceptionlnit.sql
DECLARE
e_MissingNull EXCEPTION;
PRAGMA EXCEPTION_INIT(e_MissingNull, -1400);
BEGIN
INSERT INTO students (id) VALUES (NULL);
EXCEPTION
WHEN e_MissingNull then
INSERT INTO log_table (info) VALUES ('ORA-1400 occurred');
END;

PRAGMA EXCEPTION_INIT
Oracle ,
.
SQLCODE SQLERRM , Oracle, "User- Defined Exception" ( ).

RAISE_APPLICATION JERROR
, , ,
RAISE_APPLICATION_ERROR. , , , Oracle.
RAISE_APPLICATION_ERROR :
RAISE_APPLICATION_ERROR( _, __,
[_]);

_ , -20 000 -20


999, __ , , _ . __
512 . _ . TRUE, ( ),
FALSE .
, ,
. 9:
[_) - Register, sql
/* , p_StudentID,
, p_Department p_Course. */
CREATE OR REPLACE PROCEDURE Register (

244

7
p_StudentID IN students. id%TYPE,
p_Department IN classes.department%TYPE,
p_Course IN classes.course%TYPE$ AS
v_CurrentStudents classes. current_students%TYPE;
v_MaxStudents classes. max_students%TYPE;
v_NumCredlts classes.num_credits%TYPE;
v_Count NUMBER;
BEGIN
/*
. */
BEGIN
SELECT current_students, max_students, num_credits
INTO v_CurrentStudents, v_MaxStudents, v_NumCredits
FROM classes
WHERE course = p_Course
AND department = p_Department;
/* , . */
IF v_CurrentStudents + 1 > v_MaxStudents THEN
RAISE_APPLICATION_ERROR(-20000, 'Can' 't add more students to ' | I
p_Department || ' ' || p_Course);
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN

END;

/* */
RAISE_APPLICATION_ERROR(-20001, p_Department || ' ' II
p_Course || ' doesrT't exist');

/* , */
SELECT COUNT(*)
INTO v_Count
FROM registered_students
WHERE student.id = p_StudentID
AND department = p_Department
AND course = p_Course;
IF v_count = 1 THEN
RAISE APPLICATION ERROR (-20002,

'Student ' || p_StudentID 1 1 ' is already registered for ' ||


p_Departraent I I ' ' I I p_Course);
END IF;
/* , .
. */
INSERT INTO registered_students (student_id, department, course)
VALUES (p_StudentID, p_Department, p_Course);
UPDATE students
SET current_credits = current_credits + v_NumCredits
WHERE ID = p_StudentID;
UPDATE classes

245

SET current_students = current_students + 1


WHERE course = p_Course
AND department = p_Department;
END Register;

Register RAISE_APPLICATION_ERROR . , ,
SELECT...INTO. NO_DATA_FOUND,
,
RAISE_APPLICATION_ERROR
, . , , . , RAISE_APPLICATION_ERROR,
. , ,
, ,
, SELECT ... INTO.
,
registered_students, students classes.
SQL*Plus Register . ,
( tables, sql).
-- Register.sql
SQL> -- ORA-2001 ORA-2002
SQL> exec Register(10000, ' C S ' , 999);
BEGIN Register(10000, ' O S ' , 999); END;
ERROR at line 1:

ORA-20001: CS 999 doesn't exist


ORA-06512: at "DEMO.REGISTER", line 28
ORA-06512: at line 1
SQL> exec Register(10000, 'CS', 102);
BEGIN Register(10000, 'CS', 102); END;
,

ERROR at line 1:
ORA-20002: Student 10000 is already registered for CS 102
ORA-06512: at "DEMO. REGISTER", line 40
ORA-06512: at line 1
SQL> -- MUS 410, ORA-2003
SQL> exec Register(10002, 'MUS', 410);
PL/SQL procedure successfully completed.
SQL> exec Register(10005, 'MUS', 410);
BEGIN Register(10005, 'MUS', 410); END;
ERROR at line 1:
ORA-20000: Can't add more students to MUS 410
ORA-06512: at "DEMO. REGISTER", line 23
ORA-06512: at line 1

246


, NO_DATA_FOUND:
[J Register.sql
SQL> BEGIN
2
RAISE NO_DATA_FOUND;
3 END;
4 /
BEGIN
*

ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 2

Oracle . ,
ORA-6512, , . RAISE_
APPLICATION_ERROR
, Oracle.
,

.


,
PL/SQL. , ,
. ,
? , () (exception
propagation).

,


PL/SQL, , ,
:
1.
, ,
.
2. ,
. 1. , ,
SQL*Plus.

247

, ,
(enclosing block). , .. .
:
DECLARE

- .
BEGIN
DECLARE
- 1, .
BEGIN

END;
BEGIN
- 2,
- . ,
- .

END;
- .

END;

. , 1 2, .
,
:
BEGIN

- .
- . .
F(...);
EXCEPTION
WHEN OTHERS THEN

- , F, .

END;

F ,
,
, .
1, 2 3.

248

1
1. .
.
DECLARE
A EXCEPTION;
BEGIN

BEGIN

RAISE A;
EXCEPTION
WHEN A THEN

END;

END;

2
2 .
;
1. .
DECLARE
A EXCEPTION;
EXCEPTION;
BEGIN
BEGIN
RAISE ;
EXCEPTION
WHEN A THEN


.

.

END;

EXCEPTION
WHEN THEN
END;



.

,
.

249

3
2 .
,
. 2 , ,
.
DECLARE
A EXCEPTION;
EXCEPTION;
EXCEPTION;
BEGIN
BEGIN ^
RAISE ;
EXCEPTION
WHEN A THEN
END;

EXCEPTION
WHEN THEN


.

,

.

END;



.


.

,

, .
, . , .
4 5.

4
VALUE_ERROR

v_Number NUMBER(3) := 'ABC'

250

.
OTHERS, . ,
(. 5).

DECLARE
vjlumber NUMBER (3) = 'ABC
BEGIN



VALUE_ERROR.

OTHERS, .

EXCEPTION
WHEN OTHERS THEN



VALUE ERROR.

END;

5
4,
VALUE_ERROR.
, OTHERS,
,
.

BEGIN
DECLARE
vjumber NUMBER (3)
BEGIN

EXCEPTION
WHEN OTHERS THEN

END;
EXCEPTION
WHEN OTHERS THEN
END;

:= 'ABC




VALUE ERROR.

OTHERS
.



.


,
.

251

,

, RAISE,
. ,
. ,
. , , . 6, 7 8.

6
, . .
, . 5,
, (. 7).
DECLARE
A EXCEPTION;
EXCEPTION;
BEGIN
RAISE *
EXCEPTION
WHEN A THEN
RAISE *
WHEN THEN
END;

.

,
.
,
.
.


.

7
6, . , .
?.

252

BEGIN
DECLARE
A EXCEPTION; * -
EXCEPTION;
BEGIN
RAISE A;
EXCEPTION
WHEN A THEN
RAISE B;
S
WHEN THEN *"

^
^
^


,

.


, .

.

EXCEPTION
WHEN THEN

END;


.
,

.

8
6 7, RAISE ,
. . , , ,
.
INSERT COMMIT. , INSERT - (. 4).
DECLARE

A EXCEPTION;
BEGIN
RAISE A;
EXCEPTION
WHEN A THEN
INSERT INTO logjrable (info) VALUES
('Exception A occurred');
COMMIT;
RAISE;
END;

.

,
.



.

,

.

253




.
, , , , .


. , , ,
. :
)

- OutOfScope.sql
SQL> BEGIN

2
DECLARE
3
eJJserDefinedException EXCEPTION;
4
BEGIN
5
RAISE e_UserDefinedException;
6 END;
7 EXCEPTION
8
/* e_UserDefinedException ;
9
OTHERS. */
10 WHEN OTHERS THEN
11
/* ,
12
. */
13
RAISE;
14 END;
15 /
BEGIN
*

ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at line 13
, , ,
, , RAISE_APPLICATION_ERROR (. ). Globals e _ U s e r D e f i n e d E x c e p t i o n ,
. :
Q OutOf Scope, sql
CREATE OR REPLACE PACKAGE Globals AS
/* .

. ,

254

. */
/* , */
eJJserDefinedException EXCEPTION;
END Globals;

Globals :
| - OutOfScope.sql
BEGIN
BEGIN
RAISE Globals.eJJserDefinedException;
END;
EXCEPTION
/* e_UserDefinedException ,
. */
WHEN Globals.eJJserDefinedException THEN
/* ,
. */
RAISE;
END;
, Globals
, PL/SQL (. 9 10).


, .
OTHERS, . ,
, :
rj DECLARE

vJrrrorNumber NUMBER;
vJErrorText VARCHAR2(200);

-
-
- .

BEGIN
/* */
EXCEPTION
WHEN OTHERS THEN
/* ,
. /
vJ^rrorNumber := SQLCODE;
vJ^rrorText := SUBSTR(SQLERRM, 1, 200);
INSERT INTO log_table (code, message, info) VALUES
(vJErrorNumber, vJErrorText, 'Oracle error occurred at' 1 1
TO_CHAR(SYSDATE, 'DD-MON-YY HH24:MIiSS 1 ));
END;

255


, SQL-
,
. :
[J

BEGIN
SELECT . . .
SELECT . . .
SELECT . . .
EXCEPTION
WHEN NO_DATA_FOUND THEN

- SELECT ?
END;

.
, SQL-:
] DECLARE^
-
v_SelectCounter NUMBER := 1;
BEGIN
SELECT .. .
v_SelectCounter := 2;
SELECT , . .
v_SelectCounter := 3;
SELECT .. .
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO log_table (info) VALUES ('No data found in select' [ |
v_SelectCounter);
END;
:
rj BEGIN
BEGIN
SELECT . . .
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO log_table (info) VALUES ( ' N o data found in
select 1');
END;
BEGIN
SELECT . . .
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO log_table (info) VALUES ('No data found in
select 2 ' ) ;
END;
BEGIN

256

SELECT . . .
EXCEPTION
WHEN NO_DATA_FOUND THEN

INSERT INTO log_table (info) VALUES ( ' N o data found in


select 3 ' ) ;

END;
END;


, , , ,
. PL/SQL DBMS_UTILITY.
FORMAT_CALL_STACK, VARCHAR2,
(call stack).
, , :
Q ErrorPkg.sql
CREATE OR REPLACE PROCEDURE AS
v_CallStack VARCHAR2(2000);
BEGIN
v_CallStack := DBMS_UTILITY.FORMAT_CALL_STACK;
INSERT INTO temp_table (char_col) VALUES (v_CallStack);
INSERT INTO temp_table (num_col)
VALUES

(-1);

END C;

CREATE OR REPLACE PROCEDURE AS


BEGIN
C;
END B;
CREATE OR REPLACE PROCEDURE A AS
BEGIN
B;
END A;
, ,
.
:
Q

- PL/SQL Call Stack Object Line object


Handle Number name
16998fO
4 Procedure
1699caO
3 Procedure
169f918
3
Procedure
1667efO
1 Anonymous

EXAMPLE.
EXAMPLE.
EXAMPLE.A
block

257

FORMAT_CALL_STACK, DBMS_UTILITY.FORMAT_
ERROR_STACK . ,
, .

.
rj -- ErrorPkg.sql
CREATE TABLE errors (
module
VARCHAR2(50),
seq_number
NUMBER,
error_number
NUMBER,
errorjnesg
VARCHAR2(100),
error_stack
VARCHAR2(2000),
call_stack
VARCHAR2(2000),
timestamp
DATE,
PRIMARY KEY (module, seq_number));
CREATE TABLE call_stacks (
module VARCHAR2(50),
seq_number
NUMBER,
call_order
NUMBER.
object_handle VARCHAR2(10),
line_num
NUMBER,
object_name
VARCHAR2(80),
PRIMARY KEY (module, seq_number, call_order),
FOREIGN KEY (module, seq_number) REFERENCES errors ON DELETE CASCADE);
CREATE TABLE error_stacks (
module
VARCHAR2(50),
seq_number
NUMBER,
error_order
NUMBER,
facility
CHAR(3),
error_number
NUMBER(5),
errorjnesg
VARCHAR2(100),
PRIMARY KEY (module, seq_number, error_order),
FOREIGN KEY (module, seq_number) REFERENCES errors ON DELETE CASCADE);
CREATE SEQUENCE error_seq
START WITH 1
INCREMENT BY 1;

, ErrorPkg:
| ErrorPkg.sql
/* ,
DBM9-_UTILITY. FORMAT_ERROR_STACK
DBMS_UTILITY.FORMAT_CALL_STACK.
errors,

call_stacks error_stacks. */
CREATE OR REPLACE PACKAGE ErrorPkg AS

258

7
- . HandleAll
- ,
- . _
- .
-- .
PROCEDURE HandleAll(p_Top BOOLEAN);
- (
- DBMS_OUTPUT) .
PROCEDURE PrintStacks(p_Module IN errors.moduleXTYPE,
p_SeqNum IN errors.seq_numberXTYPE);
-
- errors call_stacks.
- , .
- p_CommitFlag (TRUE),
-- .
- StoreStacks
- .
- HandleAll _ = TRUE.
PROCEDURE StoreStacks(p_Module IN errors.moduleXTYPE,
p_SeqNum OUT errors. seq_numberXTYPE,
p_CommitFlag BOOLEAN DEFAULT FALSE);
END ErrorPkg;
CREATE OR REPLACE PACKAGE BODY ErrorPkg AS
v_NewLine CONSTANT CHAR(1) := CHR(10);
v_Handled
v_ErrorStack
v_CallStack

BOOLEAN := FALSE;
VARCHAR2(2000);
VARCHAR2(2000);

PROCEDURE HandleAll(p_Top BOOLEAN) IS


BEGIN
IF p_Top THEN
v_Handled := FALSE;
ELSIF NOT vjandled THEN
vjandled := TRUE;
v_ErrorStack := DBMS_UTILITY.FORMAT_ERROR_STACK;
v_CallStack := DBMS_UTILITY.FORMAT_CALL_STACK;
END IF;
END HandleAll;
PROCEDURE PrlntStacks(p_Module IN errors.noduleXTYPE,
p_SeqNum IN errors.seq_numberXTYPE) IS
v_TimeStamp errors. timestamp%TYPE;
v_ErrorMsg errors. error_mesg%TYPE;
CURSOR c_CallCur IS
SELECT object_handle, line_num, object_name
FROM call_stacks
WHERE module = p_Module

259

AND seq_number = p_SeqNum


'ORDER BY call_order;
CURSOR c_ErrorCur IS
SELECT facility, error_number, error_mesg
FROM error_stacks
WHERE module = p_Module
AND seq_number = p_SeqNum
ORDER BY error_order;
BEGIN
SELECT timestamp, errorjnesg
INTO v_TimeStamp, v_ErrorMsg
FROM errors
WHERE module = p_Module
AND seq_number = p_SeqNum;
- .
DBMS_OUTPUT.PUT(TO_CHAR(v_TimeStamp, ' DD-MON-YY HH24:MI:SS'));
DBMSJJUTPUT.PUTC Module: ' | p_Module);
. DBMS_OUTPUT.PUT(' Error || p_SeqNum || ': ');
DBMS_OUTPUT.PUT_LINE(v_ErrorMsg);
-- .
DBMS_OUTPUT.PUT_LINE('Complete Call Stack:');
DBMS_OUTPUT.PUT_LINE(' Object Handle Line Number Object Name');
DBMS_OUTPUT.PUT_LINE(' --');
FOR v_CallRec in c_CallCur LOOP
DBMS_OUTPUT.PUT(RPAD(' ' | v_CallRec.object_handle, 15));
DBMS_OUTPUT.PUT(RPAD(' ' || TO_CHAR(v_CallRec.line_num), 13));
DBMS_OUTPUT.PUT_LINEC ' | | v_CallRec.object_name);
END LOOP;
- .
DBMS_OUTPUT.PUT_LINE('Complete Error Stack:');
FOR v_ErrorRec in c_ErrorCur LOOP
DBMS_OuTPUT.PUT(' ' | | v_ErrorRec.facility | | ' - ' ) ;
DBMS_OUTPUT.PUT(TO_CHAR(v_ErrorRec.error_number) | | ' : ' ) ;
DBMS_OUTPUT.PUT_LINE(v_ErrorRec.error_mesg);
END LOOP;
END PrintStacks;
PROCEDURE StoreStacks(p_Module IN errors.moduleXTYPE,
p_SeqNum OUT errors.seq_number!nTPE,
p_ComnitFlag BOOLEAN DEFAULT FALSE) IS

v_SeqNum

NUMBER;

v_Index
v_Length
v_End

NUMBER;
NUMBER;
NUMBER;

v_Call
VARCHAR2(100);
v_Ca!10rder NUMBER := 1;

260

v_Handle
call_stacks.object_handle%TYPE;
v_LineNum
call_stacks.line_num%TYPE;
v_ObjectName call_stacks.object_name%TYPE;
v_Error
v_ErrorOrder
v_Facility
v_ErrNum
v_ErrMsg

VARCHAR2(120);
NUMBER := 1;
error_stacks.facility%TYPE;
error_stacks.error_number%TYPE;
error_ stacks. errorjnesg%TYPE;

v_FirstErrNum errors,error_number%TYPE;
v_FirstErrMsg errors.error_mesg%TYPE;
BEGIN
- .
SELECT error_seq.nextval
INTO v_SeqNum
FROM dual;
p_SeqNum := v_SeqNum;

- errors.
INSERT INTO errors
(module, seq_number, error_stack, call_stack, timestamp)
VALUES
(p_Module, v_SeqNum, v_ErrorStack, v_CallStack, SYSDATE);
- .
- .
- .
v_Index := 1;
- ,
- . .
WHILE v_Index < LENGTH(v_ErrorStack) LOOP
- v_End .
v_End := INSTR(v._ErrorStack, v_NewLine, v_Index);
- ,
- ,
v_Error := SUBSTR(v_ErrorStack, v_Index, v_End - v_Index);
- .
v_Index := v_Index + LENGTH(v_Error) + 1;
- :
'-: '.
- .
- -- 3 .
v_Facility := SUBSTR(v_Error, 1, 3);
- ( 4 ).
v_Error := SUBSTR(v_Error, 5);

261

- .
v_ErrNum := TO_NUMBER(SUBSTR(v_Error, 1,
INSTR(v_Error, ':') - 1));
- , ( 7 ).
v_Error := SUBSTR(v_Error, 8);
- .
v_ErrMsg := v_Error;
- ,
- .
INSERT INTO error_stacks
(module, seq_number, error_order, facility, error_number,
errorjnesg)
VALUES
(p_Module, p_SeqNum, v_ErrorOrder, v_Facility, v_ErrNum,
v_ErrMsg);
IF v_ErrorOrder = 1 THEN
v_FirstErrNum := v_ErrNum;
v_FirstErrMsg := v_Facility || ' ' |l TO_NUMBER(v_ErrNum) ||
' : ' || v_ErrMsg;
END IF;

v_ErrorOrder := v_ErrorOrder + 1;
END LOOP;
- errors, ,
UPDATE errors
SET error_number = v_FirstErrNum,
error_mesg = v_FirstErrMsg
WHERE module = p_Module
AND seq_number = v_SeqNum;
-
- . .
- ,
- , .. ,
- 'name' .
v_Index := INSTR(v_CallStack, 'name') + 5;
- ,
- . .
WHILE v_Index < LENGTH(v_CallStack) LOOP
- v_End .
v_End := INSTR(v_CallStack, v_NewLine, v_Index);
- ,
- .
v_Call := SUBSTR(v_CallStack, v_Index, v_End - vjndex);
- .
v_Index := v_Index + LENGTH(v_Call) + 1;

262

7
- ,
- ,
- .
- .
- .
v_Call := LTRIM(v_Call);
- .
v_Handle := SUBSTR(v_Call, 1, INSTR(v_Call, ' '));
- .
v_Call := SUBSTR(v_Call, LENGTH(v_Handle) + 1);
v_Call := LTRIM(v_Call);

- .
v_LineNum := TO_NUMBER(SUBSTR(v_Call, 1, INSTR(v_Call, ' ')));
- .
v_Call := SUBSTR(v_Call, LENGTH(v_LineNum) + 1);
v_Call := LTRIM(v_Call);
- .
v_ObjectName := v_Call;
- , ErrorPkg.
IF v_Ca!10rder > 1 THEN
INSERT INTO call_stacks
(module, seq_number, call_order, object_handle, line_num,
object_name)
VALUES
(p_Module, v_SeqNum, v_Ca!10rder, v_Handle r v_LineNum,
v_ObjectName);
END IF;
v_Callorder := v_Ca!10rder + 1;
END LOOP;

IF p_CommitFlag THEN
COMMIT;
END IF;
END StoreStacks;
END ErrorPkg;
temp_table ( CREATE TRIGGER),
ZERO_DIVIDE, , :
Q - ErrorPkg.sql
CREATE OR REPLACE TRIGGER temp_insert
BEFORE INSERT ON temp_table

263

BEGIN
RAISE ZERO_DIVIDE;
END temp_insert;
CREATE OR REPLACE PROCEDURE AS
BEGIN
INSERT INTO temp_table (num_col) VALUES (7);
EXCEPTION
WHEN OTHERS THEN
ErrorPkg.HandleAll(FALSE);
RAISE;

END C;
CREATE OR REPLACE PROCEDURE AS
BEGIN
C;
EXCEPTION
WHEN OTHERS THEN
ErrorPkg.HandleAll(FALSE);

RAISE;

END B;
CREATE OR REPLACE PROCEDURE A AS
v_ErrorSeq NUMBER;
BEGIN
B;
EXCEPTION
WHEN OTHERS THEN

ErrorPkg.HandleAll(TRUE);
ErrorPkg. StoreStacksCError Test 1 , v_ErrorSeq, TRUE);
ErrorPkg. PrintStacksCError Test', v_ErrorSeq);

END A;

, , ( ),
:
Q

WHEN OTHERS THEN


ErrorPkg.HandleAll(FALSE);
RAISE;

, ErrorPkg ( ) ,
. HandleAll
TRUE. ErrorPkg
, . StoreStacks e r r o r s , e r r o r _ s t a c k s
call_stacks, .
(module) (package)
.

264

, ,
StoreStacks. PrintStacks errors, DBMS_OUTPUT. ,
SQL*Plus ,
:
| rPkg.sql
SQL> SET SERVEROUTPUT ON SIZE 1000000 FORMAT TRUNCATED
SQL> exec A;

31-MAY-01 01:42:47 Module: Error Test Error #1: ORA-1476: divisor


is equal to zero
Complete Call Stack:
Object Handle Line Number Object Name
16998fO
6
procedure EXAMPLE.
1699caO
procedure EXAMPLE.
3
4
procedure EXAMPLE. A
169f918
1
16570eO
anonymous block
Complete Error Stack:'
ORA-1476: divisor is equal to zero
ORA-6512: at "DEMO.TEMP_INSERT", line 2
ORA-4088: error during execution of trigger 'DEMO.TEMP_INSERT'
PL/SQL procedure successfully completed.

, PL/SQL . PL/SQL
. ,
: Oracle
, . , , PL/SQL.
.

266

L/SQL . (collection). Oracle?


. OracleS
: (varray). OracleQi ,
.. .
.
.



PL/SQL : (.
3). , students, . .
, .
,
, Java. : ,
.
(index-by tables) PL/SQL 2.0
( Oracle? 7.0)
PL/SQL 2.3 ( Oracle? 7.3). (nested tables),
OracleS, ( (table attributes) ).
( )
SQL. PL/SQL,
.
PL/SQL.

Oracle? PL/SQL .
OracleS PL/SQL ,
.

(varray). OracleS, PL/SQL


.
, PL/SQL
.

267


.
.


Java. , PL/SQL, ( ,
). :
TYPE _ IS TABLE OF INDEX BY BINARY_INTEGER;
_ ,
%TYPE %ROWTYPE.
PL/SQL.
- indexBy.sql
DECLARE

TYPE NameTab IS TABLE OF students. first_name%TYPE


INDEX BY BINARY_INTEGER;
TYPE DateTab IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
v_Names NameTab;
v_Dates DateTab;
-'-

INDEX BY BINARYJNTEGER
,
.

, PL/SQL :
_()
_ , ,
BINARYJNTEGER, ,
BINARY_INTEGER.
PL/SQL:
| -- indexBy.sql
BEGIN
v_Names(1) ;= 'Scott';
v_Dates(-4) := SYSDATE - 1;
END;
, ,
(lvalue), ,
PL/SQL.

268

Java
PL/SQL,
:
-- indexBy.sql
DECLARE
TYPE Character-Tab IS TABLE OF VARCHAR2(10)
INDEX BY BINARY_INTEGER;

v_Characters CharacterTab;
BEGIN
- . ,
- .
, v_Characters(0) := 'Harold';
v_Characters(-7) := 'Susan';
v_Characters(3) := ' S t e v e ' ;
END;

Java,
-.
: key () value ().
BINARYJNTEGER, ,
( VARCHAR2(10)).
v_Characters
, 8.1. :
.
( ) , BINARY_INTEGER
(-2147483647...+2147483647).

. ,
, ( PL/SQL
Java, , 1).
, , .
,
BINARYJNTEGER.
, ,
BINARYJNTEGER.
8.1. v_Characters

7
3

Harold
Susan
Steve

269


'- , INSERT, . -
SELECT. , - , , PL/SQL "ORA-1403: no data found" ( ),
.
SQL*Plus:
[_] indexBy.sql
SQL> DECLARE
2
TYPE NumberTab IS TABLE OF NUMBER
3
INDEX BY BINARY_INTEGER;
4
v_Numbers NumberTab;
5 BEGIN
6
- .
7
FOR v_Count IN 1..10 LOOP
8
v_Numbers(v_Count) := v_Count * 10;
9
END LOOP;
10
11
- .
12
DBMS_OuTPUT.PuT_LINECTable elements: ');
13
FOR v_Count IN 1..10 LOOP
14
DBMS_OUTPUT.PUT_LINEC v_Numbers(' || v_Count | ' ) : ' ||
15
v_Numbers(v_Count));
16
END LOOP;
17

18
19
20
21
22
23
24

- v_Numbers(11).
- , NO_DATA_FOUND.
BEGIN
DBMS_OuTPUT.PUT_LINE('v_Numbers(11): ' | | v_Numbers(11));
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT. PUT_LINE(

25
26 END;
27 END;
28 /

'No data found reading v_Numbers(11)!');

Table elements:
v_Numbers(1): 10
v_Numbers(2): 20
v_Numbers(3): 30
v_Numbers(4): 40
v_Numbers(5): 50
v_Numbers(6): 60
v_Numbers(7): 70
v_Numbers(8): 80
v_Numbers(9): 90
v_Numbers(10): 100

270
No data found reading v_Nurnbers(11)!
PL/SQL procedure successfully completed.

DBMS_OUTPUT 2,
PL/SQL
7.

DELETE
(. ).

Oracle? 7.3
. OracleS , 19
.
, :
tabRecord.sql
DECLARE

TYPE StudentTab IS TABLE OF students%ROWTYPE


INDEX BY BINARY_INTEGER;
/* v_Students . */
v_Students StudentTab;
BEGIN
/* 10001
v_Students(10001). */
SELECT *
INTO v_Students(10001)
FROM students
WHERE id = 10001;
/* v_Students(1) . */
v_Students(1).first_name := ' L a r r y ' ;
v_Students(1),last_name := 'Lemon';

END;

, :
().
OracleS , :
- tabObject.sql
CREATE OR REPLACE TYPE MyObject AS OBJECT (
fieldl NUMBER,
field2 VARCHAR2(20),
fields DATE);

271

DECLARE
TYPE ObjectTab IS TABLE OF MyObject
INDEX BY BINARY INTEGER;
/* v_0bject MyObject */
v_0bjects ObjectTab;
BEGIN
/* v_0bjects(1) .
* . */
v_0bjects(1) := MyObjectd, NULL, NULL);
v_0bjects(1).field2 := 'Hello World!';
v_0bjects(1). fields := SYSDATE;
END;

SOL
CREATE TYPE.
.
12.


. , :
(. ). ,
, , , . ,
. , ,
, ,
2 ,
.
:
TYPE _, IS TABLE OF _, [NOT NULL];
_, , _
. , , ,
%TYPE, BOOLEAN, NCHAR,
NCLOB, NVARCHAR2 REF CURSOR. OracleQf TABLE VARRAY.
19 (. ). NOT NULL,
NULL.

272



INDEX BY BINARY'JNTEGER.
, ,
.

.
nested.sql
DECLARE
- ,
TYPE ObjectTab IS TABLE OF MyObject;
-- , %ROWTYPE
TYPE StudentsTab IS TABLE OF studerits%ROWTYPE;

- , ,
v_ClassList StudentsTab;
v_ObjectList ObjectTab;

MyObject .

.
(. )
, PL/SQL,
NULL. NULL- "ORA-6531: Reference to uninitialized collection" ( ).

COLLECTION_IS_NULL. :
] - nested.sql
BEGIN
-
- COLLECTION_IS_NULL, v_ObjectList
- NULL.
v_ObjectList(1) :=
MyObject(-17, 'Goodbye', TO_DATE('01-01-200V, 'DD-MM-YYYY'));
END;
? -.
, . ,
,
.
, 1. SQL*Plus :

273

Q tConstruct.sql
SQL> DECLARE
2 TYPE NumbersTab IS TABLE OF NUMBER;
3
4
- .
5 v_Tab1 NumbersTab := NumbersTab(-t);

7
- .
8 v_Primes NumbersTab := NunbersTab(1, 2, 3, 5, 7);
9
10 -- .
11 v_Tab2 NumbersTab := NumbersTabQ;
12 BEGIN
13 - v_Tab1(1). ,
14 -- v_Tab(1) (-1), .
15 v_Tab1(1) := 12345;
16
17
- v_Primes.
18 FOR v_Count IN 1..5 LOOP
19
DBMS_OUTPUT.PUT(v_Primes(v_Count) || ' ');
20
END LOOP;
21
DBMS_OUTPUT.NEW_LINE;
22 END;
23 /
12357

PL/SQL procedure successfully completed.


v_Tab2 :
[J -- .
v_Tab2 NumbersTab := NumbersTabQ;

v_Tab2 .
,
NULL-. SQL*Plus:
]

~ nullTable.sql
SQL> DECLARE
2
TYPE WordsTab IS TABLE OF VARCHAR2(50);
3
3
- NULL-.
4
v_Tab1 WordsTab;
5
5
- , NULL.
6
v_Tab2 WordsTab := WordsTabQ;
7 BEGIN

8
9
10
11

IF v_Tab1 IS NULL THEN


DBMS_OUTPUT.PUT_LINE('v_Tab1 is NULL');
ELSE
DBMS_OUTPUT.PUT_LINECv_Tab1 is not N U L L ' ) ;

274
12
END IF;
13
13 . IF v_Tab2 IS NULL THEN
14
DBMS_OUTPUT.PUT_LINE('v_Tab2 is N U L L ' ) ;
15
ELSE
DBMS_OUTPUT.PUT_LINECv_Tab2 is not NULL');
16
17
END IF;
18 END;
19 /
v_Tab1 is NULL
v_Tab2 is not NULL
PL/SQL procedure successfully completed.


, , .
, PL/SQL "ORA-6533: Subscript
beyond count" ( ), SUBSCRIPT_BEYOND_COUNT.
:
tabAssign.sql.
SQL> DECLARE
2 TYPE NumbersTab IS TABLE OF NUMBER;
3 v_Numbers NumbersTab := NumbersTab(1, 2, 3);
4. BEGIN
5
- v_Numbers 3 .
6 - .
7 v_Numbers(1) := 7;
8 v_Numbers(2) := -1;
9
10
- ORA-6533.
11 v_Numbers(4) := 4;
12 END;
13 /
DECLARE
ERROR at line 1:
ORA-06533: Subscript beyond count
ORA-06512: at line 11


EXTEND (. ).


, (varray, varying
array, variable length array), ,
Java.

275

,
.
, .

; , 1 , .
2 .
, Java, , , .

:
TYPE _1$ (VARRAY | VARYING ARRAY] (_)
OF _ [NOT NULL];
_ , _ , , _ ,
PL/SQL. ,
%TYPE, BOOLEAN, NCHAR,
NCLOB, NVARCHAR2, REF CURSOR. 19 TABLE VARRAY. :
Q varray.sql
DECLARE
- .
- , null.
TYPE NumberList IS VARRAY(10) OF NUMBER(3) NOT NULL;
-- PL/SQL.
TYPE StudentList IS VARRAY(IOO) OF students%ROWTYPE;
-- .
TYPE ObjectList IS VARRAY(25) OF MyObject;

, . , ,
, .
SQL*Plus:
| Construct.sql
SQL> DECLARE
2
- .
3
TYPE Numbers IS VARRAY(20) OF NUMBER(3);
4

276

8
4 -- NULL.
5 v_NullList Numbers;
6
6
- 2 .
7 v_List1 Numbers := Numbers(1, 2);
8
8
- 1 , NULL
9 v_List2 Numbers := Numbers(NULL);
10 BEGIN
11 IF v_NullList IS NULL THEN
12
DBMS_OUTPUT.PUT_LINE('v_NullList is NULL');
13 END IF;
14
14 IF v_List2(1) IS NULL THEN
15
DBMS_OUTPUT.PUT_LINE('v_List2(1) is NULL');
16 END IF;
17 END;
18 /
v_NullList is NULL
v_List2(1) is NULL
PL/SQL procedure successfully completed.

, ,
. ,
, "ORA-6533: Subscript beyond count" ( ). SQL*Plus:

) varAssign.sql
SQL> DECLARE
2
TYPE Strings IS VARRAY(5) OF VARCHAR2(10);
3
4
- , .
5
v_List Strings :=
6
Strings('0ne', 'Two', 'Three');
7 BEGIN

8
- 1 3,
9 - .
10 v_List(2) := 'TWO';
11
12
- ; ORA-6533.
13 v_List(4) := '!!!';
14 END;
15 /
DECLARE
*

ERROR at line 1:
ORA-06533: Subscript beyond count
ORA-06512: at line 12

277

,
EXTEND (. ).

,
.

"ORA-6532: Subscript outside of limit" (
), SUBSCRIPT_OUTSIDE_LIMIT. :

J vAssign.sql

SQL> DECLARE
2
TYPE Strings IS VARRAY(5) OF VARCHAR2(10);

- ,
v_List Strings :=
5 Strings('One', ' T w o ' , 'Three', ' F o u r ' ) ;
BEGIN
7
- 1 4, .
8 v_List(2) := ' T W O ' ;
3
4

9
10
- 5
11
-- .
12 v_List.EXTEND;
13 v_List(5) := 'Five';
14
15
- 6 .
16
- ORA-6532.
17 v_list.EXTEND;
18 END;
19 /
DECLARE
ERROR at line 1:
ORA-06532: Subscript outside of limit
ORA-06512: at line 17


. 19 , .. .
" ". , , ,
. .

278

-- multilevel.sql
DECLARE

-
TYPE tjlumbers IS TABLE OF NUMBER
INDEX BY BINARYJMEGER;
- , t_Numbers.
- .
TYPE t_MultiNumbers IS TABLE OF t_Numbers
INDEX BY BINARY_INTEGER;
--
TYPE t_MultiVarray IS VARRAY(10) OF t_Numbers;
--
TYPE t_MultiNested IS TABLE OF t_Numbers;
v_MultiNumbers t_MultiNumbers;

, :
multilevel.sql
BEGIN
vJlultiNumbers (1) (1) := 12345;
END;



. 8.2.
8.2.

OracleT.O,
7.3



Oracle7.3

OracleS

OracleS




Oracle7.3,








Oracle7.3,





279

8.2. ()







NULL


NO_DATA_FOUND

PL/SQL






NULL


,




;

NULL



SUBSCRIPT_BEYOND_COUNT

PL/SQL



SUBSCRIPT_BEYOND_COUNT

PL/SQL

CREATE TYPE'

CREATE TYPE*

CREATE TYPE " ".


:
( ) PL/SQL .
(
PL/SQL).
.
:
,
.
,
.

:
.

.

280

, ,
.
:
SQL ,
.

1...2147483647, -2147483647... 2147483647,
.. , .
NULL ( IS NULL).
/ .
,
EXTEND TRIM (. ).
PL/SQL ( ), ( ).



PL/SQL.
( ) .
.



, .


, PL/SQL,
SQL. , PL/SQL
CREATE TYPE, . :
Q - typeLocation.sql
SQL> - , SQL PL/SQL.
SQL> CREATE OR REPLACE TYPE NameList AS
2 VARRAY(20) OF VARCHAR2(30);
3 /

281

Type created.
SQL> DECLARE
2
-- .
3
TYPE DateList IS VARRAY(10) OF DATE;
4
f
<
- DateList NameList,
5
v_Dates DateList;
6
v_Names NameList;
7 BEGIN
8
NULL;
9 END;
10 /
PL/SQL procedure successfully completed.
SQL> DECLARE

2
- NameList PL/SQL,
3
- .
4
v_Names2 NameList;
5 BEGIN
6
NULL;
7 END;
8 /

PL/SQL procedure successfully completed.

CREATE OR REPLACE TYPE SQL*Plus


/, PL/SQL
SQL*Plus
2.

, ( CREATE OR REPLACE
TYPE), PL/SQL,
, . ,
(. ).
, PL/SQL,
. ,
, PL/SQL,
.
.
books , , .
:
) tables, sql
CREATE TABLE books (
catalog_number NUMBER(4) PRIMARY KEY,
title
VARCHAR2(40),
author!
VARCHAR2(40),
author2
VARCHAR2(40),

282

authors
author4

VARCHAR2(40),
VARCHAR2(40)

catalog_number ,
author"!. . ,author4
", ". books tables, sql:
rj INSERT INTO books (catalog_number, title, authoVD
VALUES (1000, "Oracle8i Advanced PL/SQL Programming',
'Urman, Scott');
INSERT INTO books (catalog_number, title, authorl, author2, author3)
VALUES (1001, 'OracleSi: A Beginner' 's Guide' ,
'Abbey, Michael', 'Corey, Michael J . ' ,
'Abramson, Ian');
INSERT INTO books (catalog_number, title, authorl, author2, authors, author4)
VALUES (1002, 'OracleS Tuning',
'Corey, Michael J . ' , 'Abbey, Michael',
'Dechichio, Daniel J . ' , 'Abramson, Ian');
INSERT INTO books (catalog_number, title, authorl, author2)
VALUES (2001, 'A History of the W o r l d ' ,
'Arlington, Arlene', 'Verity, Victor');

INSERT INTO books (catalog_number, title, authorl)


VALUES (3001, 'Bach and the Modern World', Too, Fred');
INSERT INTO books (catalog_number, title, authorl)
VALUES (3002, 'Introduction to the Piano',
'Morenson, Mary');


.
.
. :
]

- tables. sql
CREATE OR REPLACE TYPE BookList AS VARRAY(10) OF NUMBER(4);

CREATE TABLE classjnaterial (


department
CHAR(3),
course
NUMBER(3),
required_reading BookList

283

,
4 ,
LOB. OracleSi
LOB CREATE TABLE.
LOB 12,
CREATE TABLE "SQL Reference Guide".
class_material ,
. . - ,
CREATE TYPE. classjnaterial (
) . 8.1. , ( ) required_reading.
classjnaterial

Department

Course

MUS
CS
HIS

100
102
101

Required Reading
3001 | 3002
1000

1001 | 1002
2001

. 8.1.

,
. . . :
)

- tables, sql
CREATE OR REPLACE TYPE StudentList AS TABLE OF NUMBER(5);
CREATE TABLE library_catalog (
catalog_number NUMBER(4),
FOREIGN KEY (catalog_number) REFERENCES books(catalog_number),
num_copies
NUMBER,
num_out
NUMBER,
checked_out
StudentList)
NESTED TABLE checked_out STORE AS cojtab;

library_catalog , , ,
, .
:
,
.
, CREATE TYPE.

284


NESTED TABLE,
.
(store table) , .
, .
checked_out (REF) co_tab,
. l i b r a r y _ c a t a l o g . 8.2.
library_catalog checked_out (REF)
co_tab.
Catalog Number
1000
1001
1002
2001
3001
3002

library_catalog
Mum Copies Num Out
20
3
20
3
3
10
50
0
5
0
1
5

Checked out

*^^5
*\
\
\
V

. 8.2.

( co_tab)

, .
, user_tables,
.

Oracle "ORA-22812: Cannot reference nested table
column's storage table" (
).
SQL-,
.
NESTED TABLE CREATE
TABLE "Oracle SOL Reference".

tab

285


SQL- DML
.
, .
PL/SQL, SQL (. "SQL- TABLE").
INSERT
INSERT.
. , PL/SQL.
class_material (.
. 8.1):
] - collectionDML.sql
DECLARE
v_CSBooks Booklist := BookList(1000, 1001, 1002);
v_HistoryBooks Booklist := BookList(2001);
BEGIN
- INSERT 2
-- .
INSERT INTO classjnaterial
VALUES CMUS', 100, BookList(3001, 3002));
- INSERT
-- 3 .
INSERT INTO classjnaterial VALUES CCS', 102, v_CSBooks);
- INSERT
- 1 .
INSERT INTO classjnaterial VALUES ('HIS 1 , 101, v_HistoryBooks);
END;

UPDATE
UPDATE. l i b r a r y _
catalog , . 8.2:
Q -- collectionDML.sql
DECLARE
v_StudentList1 Studentlist := Studentlist(10000, 10002,
v_Studentlist2 Studentlist := Studentlist( 10000, 10002,
v_Studentlist3 Studentlist := Studentlist(10000, 10002,
BEGIN
- NULL-.
INSERT INTO library_catalog (catalog_number, num_copies,
VALUES (1000, 20, 3);
INSERT INTO library_catalog (catalog_number, num_copies,
VALUES (1001, 20, 3);
INSERT INTO library_catalog (catalog_number, num_copies,

10003);
10003);
10003);
num_out)
num_out)
num_out)

286

VALUES (1002, 10, 3);


INSERT INTO library_catalog (catalog_number, num_copies, num_out)
VALUES (2001, 50, 0);
INSERT INTO library_catalog (catalog_number, num_copies, num_out)
VALUES (3001, 5, 0);
INSERT INTO library_catalog (catalog_number, num_copies, num_out)
VALUES (3002, 5, 1);

- PL/SQL.
UPDATE library_catalog
SET checked_out = v_StudentList1
WHERE catalog_number = 1000;
UPDATE library_catalog
SET checked_out = v_StudentList2
WHERE catalog_number = 1001;
UPDATE library_catalog
SET checked_out = v_StudentList3
WHERE catalog_number = 1002;
- , .
UPDATE library_catalog
SET checked_out = StudentList(10009)
WHERE catalog_nunber = 3002;
END;
DELETE
DELETE , , :
_| -- collectionDML.sql
DELETE FROM library_catalog
WHERE catalog_number = 3001;

SELECT
, , PL/SQL SELECT,
.
PrintRequired,
, , ,
SELECT
PL/SQL, :
| - PrintRequired.sql
CREATE OR REPLACE PROCEDURE PrintRequired(
p_Department IN classjnaterial.department%TYPE,
p_Course IN class_material.course%TYPE) IS
v_Books classjnaterial.required_reading%TYPE;
v_Title books.title%TYPE;
BEGIN
-- .
SELECT required_reading

287

INTO v_Books
FROM class_material
WHERE department = p_Department
AND course = p_Course;
DBMS_OUTPUT.PUTCRequired reading for ' || RTRIM(p_Department));
DBMS_OUTPUT.PUT_LINE(' ' || p_Course || ' : ' ) ;
- .
FOR v_Index IN 1. ,v_Books.COUNT LOOP
SELECT title
INTO v_Title
FROM books
WHERE catalog_number = v_Books(v_Index);
DBMS_OUTPUT.PUT_LINE(
' ' II v_Books(v_Index) || ' : ' || v_Title);
END LOOP;
END PrintRequired;

class_material . 8.1.
PrintRequired, :
Q - PrintRequired.sql
SOL> DECLARE

2 CURSOR c_Courses IS
3
SELECT department, course
4
FROM classjnaterial
5
ORDER BY department;
6 BEGIN
7
FOR v_Rec IN c_Courses LOOP
8
PrintRequired(v_Rec.department, v_Rec.course);
9
END LOOP;
10 END;

11 /

Required reading for CS 102:


1000: OracleSi Advanced PL/SQL Programming
1001: OracleSi: A Beginner's Guide
1002: OracleS Tuning
Required reading for HIS 101:
2001: A History of the World
Required reading for MUS 100:
3001: Bach and the Modern World
3002: Introduction to the Piano
PL/SQL procedure successfully completed.

PL/SQL, 1
, .
COUNT.
Library. PrintCheckedOut, ,
:

288

Library.sql
CREATE OR REPLACE PACKAGE Library AS

- , .
PROCEDURE PrintCheckedOut(
p_CatalogNumber IN library_catalog.catalog_number%TYPE);

END Library;

CREATE OR REPLACE PACKAGE BODY Library AS


PROCEDURE PrintCheckedOut(
p_CatalogNumber IN library_catalog.catalog_number%TYPE) IS
v_StudentList StudentList;
v_Student students%ROWTYPE;
v_Book books%ROWTYPE;
v_FoundOne BOOLEAN := FALSE;
BEGIN
- PL/SQL.
SELECT checked_out
INTO v_.StudentList
FROM library_catalog
WHERE catalog_number = p_CatalogNumber;
SELECT *
INTO v_Book
FROM books

WHERE catalog_number = p_Catalog.Number;


DBMS_OUTPUT.PUT_LINE(

'Students who have ' || v_Book.catalog_nunlber 1 1 ': ' II


v_Book.title || ' checked out: ');
-
- .
IF v_StudentList IS NOT NULL THEN
FOR v_Index IN 1..v_StudentList.COUNT LOOP
v_FoundOne := TRUE;
SELECT *
INTO v_Student

FROM students
WHERE ID = v_StudentList(v_Index);
DBMS_OUTPUT.PUT_LINE(' ' || v_Student.first_name | | ' ' ||
v_Student.last_name);
END LOOP;
END IF;
IF NOT v_FoundOne THEN
DBMS_OUTPUT.PUT_LINEC None');
END IF;
END PrintCheckedOut;
END Library;

289

L i b r a r y . PrintCheckedOut, , library_catalog , . 8.2:


| - callL.ibrary.sql
SQL> BEGIN

Library.PrintCheckedOut(1000);

3 END;
4 /

Students who have 1000: Oracle8i Advanced PL/SQL Programming checked out:
Scott Smith
Joanne Junebug
Manish Murgatroid
PL/SQL procedure successfully completed.


, , SQL,
PL/SQL, , ,
. ,
, 1. ,
. .
:
] nonsequential.sql
CREATE OR REPLACE TYPE DateTab AS
TABLE OF DATE;
/
CREATE TABLE famousjJates (
key
VARCHAR(IOO) PRIMARY KEY,
date_list
DateTab)
.NESTED TABLE date_list STORE AS dates_tab;

PL/SQL:
Q -- nonsequential.sql
DECLARE
- 5 .
v_Dates DateTab := DateTab(TO_DATE('04-JUL-1776',
TO_DATE('12-APR-1861',
TO_DATE('05-JUN-1968',
TO_DATE('26-JAN-1986',
TO_DATE('01-JAN-2001',

'DD-MON-YYYY'),
' DD-MON-YYYY'),
'DD-MON-YYYY1),
'DD-MON-YYYY'),
'DD-MON-YYYY'));

- DateTab
PROCEDURE Print(p_Dates IN DateTab) IS
v_Index BINARY_INTEGER := p_Dates.FIRST;
BEGIN
WHILE v_Index <= p_Dates.LAST LOOP
DBMS_OUTPUT.PUT(' ' || v_Index ': ');
DBMS_OUTPUT.PUT_LINE(TO_CHAR(p_Dates(v_Index),

290

'DD-MON-YYYY'));

v_Index := p_Dates. NEXT(v_Index);


END LOOP;
END Print;
BEGIN

-- 2 . ,

- 4 .
v_Dates.DELETE(2);
-

DBMS_OUTPUT.PUT_LINE( Initial value of the table: ' ) ;


Print(v_Dates);
- , .
INSERT INTO famous_dates VALUES (key, date_list);
VALUES ('Dates in American History', v_Dates);
SELECT date_list
INTO v_Dates
FROM famous_dates
WHERE key = 'Dates in American History';
DBMS_OUTPUT.PUT_LINE('Table after INSERT and SELECT: ');
Print(v_Dates);
END;

,
,
. :
Initial value of the table:
1: 04-JUL-1776
3: 05-JUN-1968
4: 26-JAN-1986
5: 01-JAN-2001 Table after INSERT and SELECT:
1: 04-JUL-1776
2: 05-JUN-1968
3: 26-JAN-1986
4: 01-JAN-2001

, .



, ,
PL/SQL SQL.
PL/SQL
Library Checkout Checkln, PL/SQL,

291

, library_catalog. PrintCheckedOut
, :
Q Library.sql
CREATE OR REPLACE PACKAGE Library AS

- p_CatalogNumber,
- p_StudentID.
PROCEDURE Checkout(
p_CatalogNumber IN library_catalog.catalog_number%TYPE,
p_StudentID IN NUMBER);
- p_CatalogNumber,
- p_StudentID.
PROCEDURE Checkln(
p_CatalogNumber IN library_catalog.catalog_number%TYPE,
p_StudentID IN NUMBER);
END Library;
CREATE OR REPLACE PACKAGE BODY Library AS

p_CatalogNumber,
p_StudentID.
PROCEDURE CheckOut(
p_CatalogNumber IN library_catalog.catalog_numberXTYPE,
p_StudentID IN NUMBER) IS
v_NumCopies library_catalog.num_copies%TYPE;
vJJumOut library_catalog.num_out%TYPE;
v_CheckedOut library_catalog.checked_out%TYPE;
BEGIN
- ,
- , .
BEGIN
SELECT num_copies, num_out, checked_out
INTO v_NumCopies, v_NumOut, v_CheckedOut
FROM library_catalog
WHERE catalog_number = p_CatalogNumber
FOR UPDATE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20000,

'There is no book with catalog number ' ||


p_CatalogNumber 1 1 ' in the library');

END;
IF v_NumCopies = v_NumOut THEN
RAISE_APPLICATION_ERROR(-20001,

'All of the copies of book ' 1 1 p_CatalogNumber 11


' are checked o u t ' ) ;

END IF;

292

8
- , .
IF v_CheckedOut IS NOT NULL THEN
FOR v_Counter IN 1. ,v_CheckedOut.COUNT LOOP
IF v_CheckedOut(v_Counter) = p_StudentID THEN
RAISE_APPLICATION_ERROR(-20002,
'Student ' |l p_StudentID || ' already has book ' ||
p_CatalogNumber || ' checked out');
END IF;
END LOOP;
END IF;
- .
IF v_CheckedOut IS NULL THEN
v_CheckedOut := StudentList(NULL);
ELSE
v_CheckedOut.EXTEND;
END IF;
-- , .
v_CheckedOut(v_CheckedOut.COUNT) := p_StudentID;
- , 1 num_out.
UPDATE library_catalog
SET checked_out = v_CheckedOut,
num_out = num_out + 1
WHERE catalog_number = p_CatalogNumber;
END Checkout;
- p_CatalogNumber,
- p_StudentID.
PROCEDURE Checkln(
p_CatalogNunber IN library_catalog.catalog_numberXTYPE,
p_StudentID IN NUMBER) IS
v_NumCopies library_catalog. num_copies%TYPE;
v_NumOut library_catalog. rium_out%TYPE;
v_CheckedOut library_catalog. checked_out%TYPE;
v_AlreadyCheckedOut BOOLEAN := FALSE;
BEGIN
- , .
BEGIN
SELECT num_copies, num_out, checked_out
INTO v_NumCopies, v_NumOut, v_CheckedOut
FROM library_catalog
WHERE catalog_number = p_CatalogNumber
FOR UPDATE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20000,
'There is no book with catalog number ' ||
p_CatalogNumber 1 1 ' i n the library');
END;

293

- , .
IF v_CheckedOut IS NOT NULL THEN
FOR v_Counter IN 1. .v_CheckedOut.COUNT LOOP
IF v_CheckedOut(v_Counter) = p_StudentID THEN
v_AlreadyCheckedOut := TRUE;
- .
v_CheckedOut.DELETE(v_Counter);
END IF;
END LOOP;
END IF;
IF NOT v_AlreadyCheckedOut THEN
RAISE_APPLICATION_ERROR(-20003,
'Student ' 1 1 p_StudentID 1 1 ' does not have book ' 1 1
p_CatalogNumber | ' checked o u t ' ) ;
END IF;
- , 1 num_out.
UPDATE library_catalog
SET checked_out = v_CheckedOut,
num_out = num_out - 1
WHERE catalog_number = p_CatalogNumber;
END Checkln;
END Library;

Checkout Checkln. class_material


library_catalog . 8.1 8.2, :
callLibrary.sql
SQL> DECLARE
2
CURSOR c_History101Students IS
3
SELECT student_ID
-1
FROM registered_students
5
WHERE department = 'HIS'
6
AND course = 101;
7
v_RequiredReading classjnaterial. required_reading%TYPE;
8 BEGIN

9
10
11
12
13
14
15
16
17
18
19
20
21

- , HIS 101,
-- , HIS 101.
SELECT required_reading
INTO v_RequiredReading
FROM classjnaterial
WHERE department = 'HIS'
AND course = 101;
- History 101.
FOR v_Rec IN c_History101Students LOOP
- .
FOR v_Index IN 1.. v_RequiredReading.COUNT LOOP

294

-- !
22
Library.CheckOut(v_RequiredReading(v_Index), v_Rec.student_ID);
23
24
END LOOP;
25 END LOOP;
\
26
- , .
27
28 Library.PrintCheckedOut(2001);
29
- , .
30
Library. Checkln(2001, 10001);
31
32 Library.Checkln(2001, 10002);
33 Library.Checkln(2001, 10003);
34
- .
3b
36 Library.PrintCheckedOut(2001);
37 END;
38 /
Students who have 2001: A History of the World checked out:
Scott Smith
Margaret Mason
Joanne Junebug
Manish Murgatroid
Patrick Poll
Timothy Taller
Barbara Blues
David Dinsmore
Ester Elegant
Rose Riznit
Rita Razmataz
Students who have 2001: A History of the World checked out:
Scott Smith
Patrick Poll
Timothy Taller
Barbara Blues
David Dinsmore
Ester Elegant
Rose Riznit
Rita Razmataz
PL/SQL procedure successfully completed.
SQL- TABLE
I OracleS/
SQL TABLE.

PL/SQL, , .
SQL PL/SQL.

295

TABLE :
TABLE( )
, .

* TABLE 18\. OracleS


THE, , TABLE.
Orac/eSi THE ,
TABLE.
, L i b r a r y . PrintCheckedOut, TABLE:
] -- LibraryOperator.sql
PROCEDURE PrintCheckedOut(
p_CatalogNumber IN library_catalog.catalog_number%TYPE) IS
v_StudentList StudentList;
v_Student students%ROWTYPE;
v_Book books%ROWTYPE;
v_FoundOne BOOLEAN := FALSE;
CURSOR c_CheckedOut IS
SELECT column_value ID
FROM TABLE(SELECT checked.out
FROM library_catalog
WHERE catalog_number = p_CatalogNumber);
BEGIN
SELECT *
INTO v_Book
FROM books
WHERE catalog_number = p_CatalogNumber;
DBMS_OUTPUT.PUT_LINE(
'Students who have ' || v_Book.catalog_number 1 1 ' : ' ||
v_Book.title || ' checked out: ');
-
- .
FOR v_Rec IN c_CheckedOut LOOP
v_FoundOne := TRUE;
SELECT *
INTO v_Student
FROM students
WHERE ID = v_Rec.ID;
DBMS_OUTPUT.PUT_LINE(' ' || v_Student.first_name 1 1 ' ' I I
v_Student.last_name);
END LOOP;
IF NOT v FoundOne THEN

296

DBMS_OUTPUT.PUT_LINE(' None');
END IF;
END PrintCheckedOut;

TABLE "Oracle SQL


Reference".
DML (
), TABLE. TABLE
, .
column_value. , class_material :
SQL> SELECT department, course, column_value
2
FROM classjnaterial, TABLE(required_reading);
DEP

COURSE

COLUMNJ/ALUE

MUS
MUS

100
100
102
102
102
101

3001
3002
1000
1001
1002
2001

cs

CG
CS
H IS

6 rows selected.


, .
. :
__.__
__ ( ), __
(. ).
, SQL-.
, , ,
:

Q tables, sql
CREATE OR REPLACE TYPE NumTab AS TABLE OF NUMBER;
CREATE OR REPLACE TYPE NumVar AS VARRAY(25) OF NUMBER;
CREATE OR REPLACE PACKAGE IndexBy AS
TYPE NumTab IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
END IndexBy;

297

IndexBy NumTab
PL/SQL IndexBy. NumTab.

9 10.
8.3.
8.3.

EXISTS

BOOLEAN

,
,

COUNT

NUMBER

LIMIT

NUMBER

FIRST
LAST

BINARY,
INTEGER

NEXT
PRIOR

BINARY.
INTEGER

EXTEND

TRIM

DELETE

TRUE,






()


,

,
,
(
NULL),

,
,
,
,

,

(
)
,

,

EXISTS
EXISTS ,
, .
:
EXISTS(n)
. , , , TRUE ( NULL).
, EXISTS SUBCRIPT_OUTSIDE_LIMIT (
) ORA-1403 (

298

), FALSE. EXISTS DELETE . :


) - exists, sql
SQL> DECLARE
2
v_NestedTable NumTab := NumTab(-7, 14.3, 3.14159, NULL, 0);
3 v_Count BINARY_INTEGER := 1;
4
v_IndexByTable IndexBy.NumTab;
5 BEGIN
6
- v_NestedTable
7
- , EXISTS .
8
LOOP
9
IF v_NestedTable.EXISTS(v_Count) THEN
10
DBMS_OUTPUT.PUT_LINE(
11
'v_NestedTable(' || v_Count || '): ' ||
12
v_NestedTable(v_Count));
13
v_Count := v_Count + 1;
14
ELSE
15
EXIT;
16
END IF;
17
END LOOP;
18
18
- .
19 v_IndexByTable(1) := -7;
20
v_IndexByTable(2) := 14.3;
21
v_IndexByTable(3) := 3.14159;
22 v_IndexByTable(4) := NULL;
23 v_IndexByTable(5) := 0;
24
24
- .
25 v_Count := 1;
26
LOOP
27
IF v_IndexByTable.EXISTS(v_Count) THEN
28
DBMS_OUTPUT.PUT_LINE(
29

'v_IndexByTableC || v_Count || ' ) : ' ||

30
v_IndexByTable(v_Count));
31
v_Count := v_Count + 1;
32
ELSE
33
EXIT;
34
END IF;
35 END LOOP;
36 END;
37 /
v_NestedTable(1): -7
v_NestedTable(2): 14.3
v_NestedTable(3): 3.14159
v_NestedTable(4):
v_NestedTable(5): 0
v_IndexByTable(1): -7
v_IndexByTable(2): 14.3

299

v_IndexByTable(3): 3.14159
v_IndexByTable(4):
v_IndexByTable(5): 0
PL/SOL procedure successfully completed.
, n- NULL, EXISTS(n) TRUE. EXISTS ,
NULL- ; FALSE.

COUNT
COUNT . COUNT
, .
SQL*Plus:
Q

count.sql
SOL> DECLARE

2
3
4
5

6
7
8
9
10
11

12

v_NestedTable NumTab := NumTabO, 2, 3);


v_Varray NumVar := NumVar(-1, -2, -3, -4);
v_IndexByTable IndexBy. NumTab;
BEGIN

- .
- : .
v_IndexByTable(1) := 1;
v_IndexByTable(8) := 8;
v_IndexByTable(-1) := -1;
v_IndexByTable(100) := 100;

13
14
15

- .
DBMS_OUTPUT.PUT_LINE(
'Nested Table Count: ' 1 1 v_NestedTable.COUNT);

16

DBMS_OuTPUT.PUT_LINE(

17
18

'Varray Count: ' || v_Varray.COUNT);


DBMS_OUTPUT.PUT_LINE(

19
'Index-By Table Count: ' 1 1 v_IndexByTable.COUNT);
20 END;
21 /
Nested Table Count: 3
Varray Count: 4
Index-By Table Count: 4
PL/SQL procedure successfully completed.
COUNT LAST
(. ), .
,
COUNT LAST -. COUNT ,
. COUNT .

300

LIMIT
LIMIT . , LIMIT
NULL. LIMIT . LIMIT
SQL*Plus:
) - limit.sql
SQL> DECLARE
2
v_Table NumTab :=NumTab(1, 2, 3);
3
v_Varray NumVar := NumVar(1234, 4321);
4 BEGIN

5
6
7
8
9
10
11
12
13

-
- .
DBMS_OUTPUT.PUT_LINECVarray limit: ' 1 1 v.Varray.LIMIT);
DBMS_OUTPUT.PUT_LINE('Varray count: ' || v_Varray.COUNT);
IF v_Table. LIMIT IS NULL THEN
DBMS_OUTPUT.PUT_LINE('Table limit is NULL');
ELSE
DBMS_OUTPUT.PUT_LINECTable limit: ' | | v_Table. LIMIT);
END IF;

14
DBMS_OUTPUT.PUT_LINE('Table count: ' || v_Table.COUNT);
15 END;
16 /

Varray limit: 25
Varray count: 2
Table limit is NULL
Table count: 3
PL/SQL procedure successfully completed.

: 25 , CREATE TYPE,
v_Varray . COUNT
(. ).

FIRST LAST
FIRST ,
LAST . FIRST
1, a LAST COUNT,
. FIRST LAST NEXT PRIOR
.

NEXT PRIOR
NEXT PRIOR
. :

301

NEXT(n)
PRIOR(n)
. NEXT(n) ,
, a PRIOR(n) , .
, PRIOR NEXT NULL. SOJL*Plus , NEXT PRIOR
FIRST LAST
:
)

collectionLoops.sql
SQL> DECLARE
2
TYPE CharTabIS TABLE OF CHARd);
3
v_Characters CharTab :=
4
CharTab('M', ' a ' , ' d ' , ' a ' , ' m ' , ' , ' , ' ',

5
6

'I', ' ' ' , ' m ' , ' ', ' A ' , ' d ' , ' a ' , 'm');

7 v_Index INTEGER;
8 BEGIN
9
- .
10 v_Index := v_Characters.FIRST;
11 WHILE v_Index <= v.Characters. LAST LOOP
12
DBMS_OUTPUT.PUT(v_Characters(v_Index));
13
v_Index := v_Characters.NEXT(v_Index);
14 END LOOP;
15 DBMS_OUTPUT.NEW_LINE;
16
17 - .
18 v_Index := v_Characters. LAST;
19 WHILE v_Index >= v_Characters. FIRST LOOP
20
DBMS_OUTPUT.PUT(v_Characters(v_Index));
21
v_Index := v_Characters.PRIOR(v_Index);
22 END LOOP;

23
DBMS_OUTPUT.NEW_LINE;
24 END;
25 /
Madam, I'm Adam
madA m'l ,madaM
PL/SQL procedure successfully completed.

FIRST, LAST, NEXT PRIOR


.

EXTEND
EXTEND
. EXTEND :
EXTEND
EXTEND(w)

302

EXTEND(rM)
EXTEND NULL
LAST + I. EXTEND () NULL, a EXTEND(n,z) .
NOT NULL, ,
NULL- .

, EXTEND ( 2 ). ,
,
LIMITCOUNT. EXTEND
SQL*Plus:
Q extend.sql
SQL> DECLARE
2
v_NumbersTab NumTab := NumTabd, 2, 3, 4, 5);
3
v_NumbersList NumVar := NumVar(1, 2, 3, 4, 5);

4 BEGIN
5
BEGIN
6
--
7
- SUBSCRIPT_BEYOND_COUNT, v_NumbersTab
8
-- 5 .
9
v_NumbersTab(26) := -7;
10
EXCEPTION
11
WHEN SUBSCRIPT_BEYOND_COUNT THEN
12
DBMSJDUTPUT. PUT_LINE(
13
'ORA-6533 raised for assignment to v_NumbersTab(26)');
14 END:
15
16
- , 30
17 -- v_NumbersTab.
18 v_NumbersTab.EXTEND(30);
19
20
- .
21 v_NumbersTab(26) := -7;
22
23
-
24
- ( LIMIT). ,
25
- SUBSCRIPT_OUTSIDE_LIMIT:
26
BEGIN
27
v_NumbersList.EXTEND(30);
28
EXCEPTION
29
WHEN SUBSCRIPT_OUTSIDE_LIMIT THEN
30
DBMS_OUTPUT.PUT_LINE(
31
32
33

'ORA-6532 raised for v_NumbersList.EXTEND(SO)');


END;

34

303

- .

35 v_NumbersList.EXTEND(20);
36
37
- .
38 v_NumbersList(25) := 25;
39 END;
40 /
ORA-6533 raised for assignment to v_NumbersTab(26)
ORA-6532 raised for v_NumbersList.EXTEND(30)
PL/SQL procedure successfully completed.
EXTEND , (
). ( DELETE, ) , .
EXTEND DELETE :
) -- extendDelete.sql
DECLARE
- 5 .
v_Nuinbers NumTab := NumTab(-2, -1, 0, 1, 2);
- .
- FIRST, LAST NEXT.
PROCEDURE Print(p_Table IN NumTab) IS
v_Index INTEGER;
BEGIN
v_Index := p_Table.FIRST;
WHILE v_Index <= p_Table.LAST LOOP
DBMS_OUTPUT.PUTCElement ' || v_Index || ': ');
DBMSJ)UTPUT.PUT_LINE(p_Table(v_Index));
v_Index := p_Table.NEXT(v_Index);
END LOOP;
END Print;
BEGIN
DBMS_OUTPUT.PUT_LINE('At initialization, v_Numbers contains');
Print(v_Numbers);
- 3. '0', .
v_Numbers.DELETE(3);
DBMS_OUTPUT.PUT_LINEC After delete, v_Numbers contains');
Print(v_Numbers);
- 2 1. 6 7.
v_Numbers.EXTEND(2, 1);
DBMS_OUTPUT.PUT_LINE('After extend, v_Numbers contains');
Print(v_Numbers);
DBMS_OUTPUT.PUT_LINE('v_Numbers.COUNT = ' || v_Numbers.COUNT);
DBMS_OUTPUT.PUT_LINE('v_Numbers.LAST = ' || v_Numbers. LAST);
END;

304

. COUNT LAST DELETE


EXTEND.
Q At initialization, v_Numbers contains
Element 1: -2
Element 2: -1
Element 3: 0
Element 4: 1
Element 5: 2
After delete, v_Numbers contains
Element 1: -2
Element 2: -1
Element 4: 1
Element 5: 2
After extend, v__Numbers contains
Element 1: -2
Element 2: -1
Element 4: 1
Element 5: 2
Element 6: -2
Element 7: -2
v_Numbers.COUNT = 6
v_Numbers.LAST = 7

TRIM
TRIM . :
TRIM ,
TRIM(n)
TRIM . . COUNT,
SUBSCRIPT_BEYOND_COUNT.
TRIM COUNT , TRIM
.
EXTEND, TRIM
, .. , DELETE.
:
Q trim.sql
DECLARE
- 7 .
v_Numbers NumTab := NumTab(-3, -2, -1, 0, 1, 2, 3);
- .
PROCEDURE Print(p_Table IN NumTab) IS
v_Index INTEGER;
BEGIN
v_Index := p_Jable. FIRST;


WHILE v_Index <= p_Table.LAST LOOP
DBMS_OUTPUT.PUT('Element ' || v_Index || ': ');
DBMS_OUTPUT.PUT_LINE(p_Table(v_Index));
v_Index := p_Table. NEXT(v_Index);
END LOOP;
DBMS_OUTPUT.PUT_LINECCOUNT = ' || p_Table.COUNT);
DBMS_OUTPUT.PUT_LINECLAST= ' || p_Table.LAST);
END Print;

BEGIN

DBMS_OUTPUT,PUT_LINE('At initialization, v_Numbers contains');


Print(v_Numbers);
-- 6.
v_Numbers.DELETE(6);
DBMS.OUTPUT.PUT_LINECAfter delete , v_Numbers contains');
Print(v_Numbers);

- 3 . 2 3,
- ( ) 1.
v_Numbers.TRIM(3);
DBMS_OUTPUT.PUT_LINE('After trim, v_Numbers contains');
Print(v_Numbers);
END;
:
At initialization, v_Numbers contains
Element 1: -3
Element 2: -2
Element 3: -1
Element 4: 0
Element 5: 1
Element 6: 2
- Element 7: 3
COUNT = 7
LAST = 7
After delete, v_Numbers contains
Element 1: -3
Element 2: -2
Element 3: -1
Element 4: 0
Element 5: 1
Element 7: 3
COUNT = 6
LAST = 7
After trim, v_Numbers contains
Element 1: -3
Element 2: -2
Element 3: -1
Element 4: 0
COUNT = 4
LAST = 4

305

306

DELETE
DELETE 1 . DELETE , (, DELETE
). DELETE :
DELETE
DELETE(n)
DELETE(m,n)
DELETE . DELETE(w) , , a DELETE(wj,w) , . DELETE
COUNT , .
, DELETE , .
DELETE :
r_J

delete.sql
DECLARE
- 10 .
v_Numbers NumTab := NumTab(10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
- .
PROCEDURE Print(p_Table IN NumTab) IS
v_Index INTEGER;
BEGIN
v_Index := p_Table.FIRST;
WHILE v_Index <= p_Table.L-AST LOOP
DBMSJXJTPUT. PUTCElement ' || v_Index || ' : ' ) ;
DBMS_OUTPUT.PUT_LINE(p_Table(v_Index));
v_Index := p_Table.NEXT(v_Index);
END LOOP;
DBMS_OUTPUT.PUT_LINE('COUNT = ' || p_Table.COUNT);
DBMS_OUTPUT.PUT_LINE('LAST = ' || p_Table.LAST);
END Print;
BEGIN
DBMS_OUTPUT.PUT_LINE('At initialization, v_Numbers contains');
Print(v_Numbers);
- 6.
DBMS_OUTPUT.PUT_LINECAfter delete(6), v_Numbers contains');
v_Numbers.DELETE(6);
Print(v_Numbers);

- 7 9.
DBMS_OUTPUT.PUT_LINE('After delete(7,9), v_Numbers contains');
v_Numbers.DELETE(7,9);
Print(v_Numbers);

END;

307

:
Q| At initialization, v_Numbers contains
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Element 6: 60
Element 7: 70
Element 8: 80
Element 9: 90
Element 10: 100
COUNT = 10
LAST = 10
After delete (6), v_Numbers contains
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Element 7: 70
Element 8: 80
Element 9: 90
Element 10: 100
COUNT = 9
LAST = 10
After delete (7,9), v_Numbers contains
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Element 10: 100
COUNT = 6
LAST = 10

.
, . , ,
. ,
.

III

PL/SOL

9
,

312

1 PL/SQL: (. 3). ( DECLARE


BEGIN) . ,
PL/SQL. ,
(, , ), ,
. . , . 10 ,
. 11
.


PL/SQL ,
, . (subprogram).
:
] AddNewStudent.sql
CREATE OR REPLACE PROCEDURE AddNewStudent (
p_FirstName students.first_name%TYPE,
p_LastName students.last_name%TYPE,
p_Major
students.major%TYPE) AS
BEGIN
- students.
- studejit_sequence
- 0
-- current_credits,
INSERT INTO students (ID, first_name, last_name,
major, current_credits)
VALUES (student_sequence.nextval, p_FirstName, p_LastName,
p_Major, 0);
END AddNewStudent;
PL/SQL:
r_j

AddNewStudent.sql
BEGIN
AddNewStudent('Zelda', 'Zudnik', 'Computer Science');
END;

313

AddNewStudent CREATE
OR REPLACE PROCEDURE.
, . PL/SQL.
(. 10).
.
, . p_FirstName 'Zelda', p_l_astName ' Z u d n i k ' , a p_Major 'Computer Science',
.
PL/SQL; .
.
, , . PL/SQL
, ( 3GL).
(. ).
PL/SQL, ,
. ,
. , AddNewStudent
.


, CREATE ( CREATE PROCEDURE, - CREATE FUNCTION).


CREATE [OR REPLACE] PROCEDURE :
CREATE [OR REPLACE] PROCEDURE _,
[ ( [{IN [ OUT |IN OUT}] ,
[{1 \ OUT |INOUT}] )] {IS | AS}
_
_ , , , _ PL/SQL, .
;
, .

314

Oracle8\ CREATE [OR REPLACE] PROCEDURE


NOCOPY(CM.
" ")
AUTHID (. 10).
, . , OR REPLACE ( )
. ,
(
DROP PROCEDURE; . ).
, . ,
OR REPLACE , CREATE Oracle: "ORA-955: Name is already used by an existing object"
( ).
CREATE, DDL, COMMIT.
IS, AS .
(body) PL/SQL, ,
. IS
AS BEGIN; (
) BEGIN EXCEPTION, EXCEPTION
END.


DECLARE .
IS AS. PL/SQL
Ada.
, :
CREATE OR REPLACE PROCEDURE _
[_] AS
/* */
BEGIN
/* */
EXCEPTION
/* */
END [_];

END. END ,
.

315


, END,
CREATE,
BEGIN-END
.

. , ( ).
PL/SQL, , . ,
( ,
, 10). PL/SQL, . ,
TRUE, 80%, FALSE
.
)

AlraostFull.sql
CREATE OR REPLACE FUNCTION AlmostFull (
p_Department
classes. department%TYPE,
p_Course
classes.course%TYPE)
RETURN BOOLEAN IS
v_CurrentStudents NUMBER;
NUMBER;
v_MaxStudents
BOOLEAN;
v_ReturnValue
CONSTANT NUMBER := 80;
v_FullPercent
BEGIN
- .
SELECT current_students, max_students
INTO v_CurrentStudents, v_MaxStudents
FROM classes
WHERE department = p_Department
AND course = p_Course;
- ,
- v_FullPercent, TRUE.
- FALSE.

IF (v_CurrentStudents / v_MaxStudents * 100) >= v_FullPercent THEN


v_ReturnValue := TRUE;
ELSE
v_ReturnValue := FALSE;

END IF;

RETURN v_ReturnValue;
END AlmostFull;

316

AlmostFull . PL/SQL, .
, IF, .
} - callFunction.sql
SQL> DECLARE
2
CURSOR c_Classes IS
3
SELECT department, course
4
FROM classes;
5 BEGIN

FOR v_ClassRecord IN c_Classes LOOP


- ,

8
9
10
11

-- .
IF AlmostFull(v_ClassRecord.department,
v_ClassRecord.course) THEN
DBMS_OUTPUT.PUT_LINE(

12
v_ClassRecord.department 1 1
||
13
v_ClassRecord.course 1 1 ' is almost full!');
14
END IF;
15
END LOOP;
16 END;

17 /

MUS 410 is almost full!


PL/SQL procedure succefully completed.

DBMS_OUTPUT.PUT_LINE
SQL*Plus ,
set serveroutput on (. 2).

,
, :
CREATE [OR REPLACE] FUNCTION _,
[( [{IN | OUT |IN OUT}] ,
[{1 \ OUT |INOUT}] )]
RETURN _ {IS | AS}
_
_ , , , _
, , _ PL/SQL,
. , . , END.
, .
,
. , ,

3t7

. ,
.

, /8\
NOCOPYn AUTHID.
RETURN RETURN
. RETURN:
RETURN ;
. , RETURN ,
, , .
RETURN .
RETURN, . RETURN
. RETURN. RETURN, , ,
p_Department p_Course.
-- Classlnfo.sql
CREATE OR REPLACE FUNCTION Classlnfo (
/* 'Full', ,
Some Room', 80%,
More Room', 60%,
Lots of Room', 60%,
Empty', . */
p_Department classes.department%TYPE,
p_Course classes.course%TYPE)
RETURN VARCHAR2 IS
v_CurrentStudents NUMBER;
v_MaxStudents NUMBER;
v_PercentFull NUMBER;
BEGIN
- .
SELECT current_students, max_students
INTO v_CurrentStudents, v_MaxStudents
FROM classes
WHERE department = p_Department
AND course = p_Course;
- .
v_PercentFull := v_CurrentStudents / v_MaxStudents * 100;

318

IF v_PercentFull = 100 THEN


RETURN 'Full';
ELSIF v_PercentFull > 80 THEN
RETURN 'Some Room';
ELSIF v_PercentFull > 60 THEN
RETURN 'More Room';
ELSIF v_PercerttFull > 0 THEN
RETURN 'Lots of Room';
ELSE

RETURN 'Empty';
END IF;
END Classlnfo;

RETURN
. RETURN
. ,
, . , OUT IN OUT,
, , (. ).


, . .
:
DROP PROCEDURE _;
:
DROP FUNCTION _;
_ , _
. ,
AddNewStudent:
DROP PROCEDURE AddNewStudent;
, DROP FUNCTION, - , DROP PROCEDURE.
DROP DDL, DROP
COMMIT. , DROP "ORA-4043: Object does not exist".


, .
, .

319


AddNewStudent
PL/SQL:
Q callANS.sql
DECLARE
- , .
v_NewFirstName students. first_name%TYPE := 'Cynthia';
v_NewLastName students. last_name%TYPE := 'Camino';
v_NewMajor students.major%TYPE := 'History';
BEGIN

- Cynthia Camino .
AddNewStudent(v_NewFirstName, v_NewLastName, v_NewMajor);
END;
v_NewFirstName, v_NewLastName, v_NewMajor AddNewStudent . (actual parameter), ,
(p_FirstName, p_LastName, p_Major),
(formal parameter). , ,
, (
). . .
.
.
,
. , PL/SQL , .
: IN (), OUT () IN
OUT ( OracleSi NOCOPY). , IN. 9.1. :

>

Mode Jest
PL/SQL
,
.

Q -- ModeTest.sql
CREATE OR REPLACE PROCEDURE ModeTest (
p_InParameter
IN NUMBER,
p_OutParameter
OUT NUMBER,
p_InOutParameter IN OUT NUMBER) IS
v_LocalVariable NUMBER:=0;

320

BEGIN
DBMS_OUTPUT.PUT_LINECInside ModeTest:');
IF (p_InParameter IS NULL) THEN
DBMS_OUTPUT.PUT('p_InParanieter is NULL');
ELSE
DBMS_OUTPUT.PUT('p_InParameter = ' || p_InParameter);
END IF;
IF (p_OutParameter IS NULL) THEN
DBMS_OUTPUT.PUTC p_OutParameter is NULL');
ELSE
DBMS_OUTPUT,PUT(' pJMParameter = ' || p_OutParameter);
END IF;
IF (p_InOutParameter IS NULL) THEN
DBMS_OUTPUT.PUT_LINE(' p_InOutParameter is NULL');
ELSE
DBMS_OUTPUT.PUT_LINEC p_InOutParameter= ' ||
p_InOutParameter);
END IF;
/* p__InParameter v_Loca!Variable.
, IN
. */
v_LocalVariable := p_InParameter; -- .
/* 7 p_InParameter. ,
IN. */
- p_InParameter := 7; .
/* 7 p_OutParameter. ,
OUT. */
p_OutParameter := 7; - .
/* pJJutParameter v_LocalVariable. !7
7.3.4 OracleS 8.0.4 ( 81)
. Oracle, 7.3.4,
, OUT.*/
v_LocalVariable := p_OutParameter; -- , .
/* p_InOutParameter v_LocalVariable.
, IN OUT. */
v_LocalVariable := p_InOutParameter; -- .
/* 8 p_InOutParameter. ,
IN OUT. */
p_InOutParameter := 8; .
DBMS_OUTPUT.PUT_LINE('At end of ModeTest:');
IF (p_InParameter IS NULL) THEN
DBMS_OUTPUT.PUTCp_InParameter is NULL');
ELSE
DBMS_OUTPUT.PUT('p_InParameter = ' || p_InParameter);

321

END IF;

IF (pJMParameter IS NULL) THEN


DBMS_OUTPUT.PUT(' pJMParameter is NULL');
ELSE
DBMS_OUTPUT.PUT( - pJMParameter = ' || pJM Parameter);
END IF;
IF .(p_InOutParameter IS NULL) THEN
DBMS_OUTPUT.PUT_LINE(' p_InOutParameter is NULL');
ELSE
DBMS_OUTPUT.PUT_LINE(' p_In(MParameter = ' ||
p_InOutParameter);
END IF;
END ModeTest;

Oracle 7.3.4 8.0.3


OUT, OracleS
8.0.4 (. " OUT").
9.1.

IN

.

PL/SQL, .. , .

, .

OUT

, ,
.
PL/SQL, ..
NULL- , ,
.
,
( OracleS/
NOCOPY; . "
").

IN OUT

IN OUT.
.

, ,
.
,
( 18/ NOCOPY,
OUT).

322

ModeTest :
- callMT.sql
DECLARE
v_In NUMBER := 1;
v_0ut NUMBER := 2;
v_InOut NUMBER := 3;
BEGIN
DBMS_OUTPUT.PUT_LINECBefore calling ModeTest:');
DBMS_OUTPUT.PUT_LINE('v_In = ' || v_In ||
' v_0ut = ' | I v_0ut 1 1
' v_InOut = ' | I v_InOut);
ModeTest(v_In, v_0ut, v_InOut);
f

DBMS_OUTPUT.PUT_LINE( After calling ModeTest:');


DBMS_OUTPUT.PUT_LINE(' v_In = ' || v_In ||
v_0ut = ' | | v_0ut 11
' v_InOut = ' 1 1 v_InOut);
END;

:
Before calling ModeTest:
v_In = 1 v_0ut = 2 v_InOut = 3

Inside ModeTest:
p_InParameter = 1 p_0utParameter is NULL p_InOutParameter = 3
At end of ModeTest:
p_InParameter = 1 p_0utParameter = 7 p_InOutParameter = 8
After calling ModeTest:
v_In = 1 v_0ut = 7 v_InOut = 8
, OUT NULL- . , IN
IN OUT .


, IN OUT OUT

( Oracle8\ NOCOPY).
. " ,
".

, , IN OUT OUT,
.
. , ModeTest v_In :

323

| callMT.sql
DECLARE
v_0ut NUMBER := 2;
v_InOut NUMBER := 3;
BEGIN
ModeTest(1, v_0ut, v_InOut);
END;

v_0ut , :
Q ~ callMT. sql
SOL> DECLARE
2
v_InOut NUMBER := 3;
3 BEGIN

ModeTestO, 2, v_InOut);

5 END;
6 /

DECLARE
*

ERROR at line 1:
ORA-06550: line 4, column 15:
PLS-00363: expression '2' cannot be used as an assignment target
ORA-06550: line 4, column 3:
PL/SQL: Statement ignored

PL/SQL . ,

p_InParameter ModeTest, :
Q PLS-363: expression 'P_INPARAMETER' cannot be used as an assignment target
( 'P_INPARAMETER'
)
OUT 7.3.4 8.0.3 OUT . , , ModeTest 8.0.3,
:
) PLS-00365: 'P_OUTPARAMETER' is an OUT parameter and cannot be read
('P_OUTPARAMETER' OUT )
9.2. OUT
Oracle
7.3.4
7.3.4
8.0.3
8.0.4

OUT

324

, OUT IN OUT. 9.2


, Oracle OUT, a
.


,
. ,
, ,
.
CHAR VARCHAR2, /
NUMBER, . , :
Q -- ParameterLength.sql
CREATE OR REPLACE PROCEDURE Parameter-Length (
p_Parameter1 IN OUT VARCHAR2(10),
p_Parameter2 IN OUT NUMBER(3,1)) AS
BEGIN
p_Pa ramete r1 := 'abcdefghijklm';
p_Parameter2 := 12.3;
END ParameterLength;

:
Q ParameterLength.sql
CREATE OR REPLACE PROCEDURE ParameterLength (
p_Parameter1 IN OUT VARCHAR2,
p_Parameter2 IN OUT NUMBER) AS
BEGIN
p_Parameter1 := 'abcdefghijklmno';
p_Parameter2 := 12.3;
END ParameterLength;

, , p_Parameter1 p_Parameter2,
. P a r a m e t e r Length :
Q ParameterLength.sql
DECLARE
v_Variable1 VARCHAR2(40);
v_Variable2 NUMBER(7,3);
BEGIN
ParameterLength(v_Variablel, v_Variable2);
END;

_ ramete r1 40 ( v_Variable1), p_Parameter2 7 3 ( v_Variable2).


, ParameterLength:

325

-- ParameterLength.sql
DECLARE
v_Variable1 VARCHAR2(10);
v_Variable2 NUMBER(7,3);
BEGIN

ParameterLength(v_Variable1, v_Variable2);
END;


, v_Variable1 , , p_Parameter1 10, 40.
ParameterLength p_Parameter1 ( v_Variable1) , 15 ,
. Oracle :
Q

DECLARE
*

ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at "DEMO.PARAMETERLENGTH", line 5
ORA-06512: at line 5

, , . ORA-6502 , . , ,
, , PL/SQL
' a b c d e f g h i j k l m n o ' .

, ORA-6502,
,
,
, ,
.
%TYPE.

% TYPE
%TYPE. %TYPE, a
, , . ParameterLength :
ParameterLength.sql
CREATE OR REPLACE PROCEDURE ParameterLength (
p_Parameter1 IN OUT VARCHAR2,
p_Parameter2 IN OUT students. current_creditsXTYPE) AS
BEGIN
p_Parameter2 := 12345;

326

END ParameterLength;

p_Parameter2 3,
current_credits. Parameter-Length , . ,
ORA-6502:
Q

ParameterLength.sql

SQL> DECLARE
2 v_Variable1 VARCHAR2(1);
3
- v_Variable2 .
4
v_Variable2 NUMBER;
5 BEGIN
6
- 12345,
7
- , ,
8
- ORA-6502.
9 ParameterLength(v_Variable1, v_Variable2);
10 END;
11 /
DECLARE
,

ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: number precision too large
ORA-06512: at "EXAMPLE.PARAMETERLENGTH", line 5
ORA-06512; at line 9

ORA-6502 Oracle3\.
OracleSi "ORA-6502:
PL/SQL numeric or value error"
. ,
, OracleSi.
,
,
. , ,
(. 7).
OUT IN OUT
. , ,
. , :
Q RaiseError.sql
/*
OUT. p_Raise ,
.

327

p_Raise , . */
CREATE OR REPLACE PROCEDURE RaiseError (
p_Raise IN BOOLEAN,
p_ParameterA OUT NUMBER) AS
BEGIN
p_ParameterA := 7;
IF p_Raise THEN
/* p_ParameterA 7,

;
7 ,
p_ParameterA. */
RAISE DUP_VAL_ON_INDEX;
ELSE
- . '
- 7.
RETURN;
END IF;
END RaiseError;

RaiseError :
| -- RaiseError.sql
DECLARE

v_TempVar NUMBER := 1;
BEGIN
DBMS_OUTPUT.PUT_LINE('Initial value: ' || vJempVar);
RaiseError(FALSE, v_TempVar);
DBMSJHJTPUT. PUT_LINECValue after successful call: ' 1 1
v_TempVar);
v_TempVar := 2;
DBMS_OUTPUT.PUT_LINECValue before 2nd call: ' 1 1 v_TempVar);
RaiseError(TRUE, v_TempVar);
EXCEPTION

WHEN OTHERS THEN


DBMS_OUTPUT.PUT_LINE('Value after unsuccessful call: ' 1 1
v_TempVar);
END;
:
r_j Initial value: 1
Value after successful call: 7
Value before 2nd call: 2
Value after unsuccessful call: 2
RaiseError v_TempVar 1. , v_TempVar
7. RaiseError v_TempVar 2. , v_TempVar
2 ( 7).

328

,
OUT IN OUT
NOCOPY (. "
NOCOPY").


: . (by reference),
. (by value),
.
, ;
( ; . 8). PL/SQL IN , IN
OUT OUT . , (. )
, . OracleSt .
NOCOPY OracleSz
NOCOPY. :
_ [] NOCOPY _

_ , (IN, OUT
IN OUT), . NOCOPY, PL/SQL , . NOCOPY , ,
(. ). :
- NoCopyTest.sql
CREATE OR REPLACE PROCEDURE NoCopyTest (
p_InParameter
IN NUMBER,
p_0utParameter
OUT NOCOPY VARCHAR2,
p_InOutParameter
IN OUT NOCOPY CHAR) IS
BEGIN
NULL;
END NoCopyTest;

NOCOPY IN , IN NOCOPY
.
NOCOPY
, ,
,
. ,

329

. RaiseError, NOCOPY:
Q - NoCopyTest.sql
CREATE OR REPLACE PROCEDURE RaiseError (
p_Raise IN BOOLEAN,
p_ParameterA OUT NOCOPY NUMBER) AS
BEGIN
p_ParameterA := 7;
IF p_Raise THEN
RAISE DUP_VAL_ON_INDEX;
ELSE
RETURN;
END IF;
END RaiseError;

, p_ParameterA
, . , R a i s e E r r o r
:
rj NoCopyTest.sql
DECLARE
vJempVar NUMBER := 1;
BEGIN
DBMS_OUTPUT.PUT_LINE('Initial value: ' || vJempVar);
RaiseError(FALSE, vJTempVar);
DBMS_OUTPUT.PUT_LINECValue after successful call: ' ||
v_TempVar);
v_TempVar := 2;

DBMS_OUTPUT.PUT_LINECValue before 2nd call: ' | v_TempVar);


RaiseError(TRUE, v_TempVar);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINECValue after unsuccessful call: ' | |
v^TempVar);
END;
, " , ".
:
Q Initial value: 1
Value after successful call: 7
Value before 2nd call: 2
Value after unsuccessful call: 7

, .
NOCOPY NOCOPY .

330

. , NOCOPY , . NOCOPY :
.
, .
, NOT NULL. , .
, PL/SQL
, ..
.
, ,
NOCOPY.
, , ,
, %ROWTYPE, .
.

(RFC, remote procedure call), .. . ,
.

RPC, NOCOPY
.
, RPC,
.

NOCOPY NOCOPY ,
.
PL/SQL, :
CopyFast.sql
CREATE OR REPLACE PACKAGE CopyFast AS

- PL/SQL- .
TYPE StudentArray IS
TABLE OF students%ROWTYPE;
- , StudentArray .
- .
PROCEDURE PassStudents1(p_Parameter IN StudentArray);
PROCEDURE PassStudents2(p_Parameter IN OUT StudentArray);
PROCEDURE PassStudentsS (p_Parameter IN OUT NOCOPY StudentArray);

,
- .
PROCEDURE Go;
END CopyFast;
CREATE OR REPLACE PACKAGE BODY CopyFast AS
PROCEDURE PassStudents1(p_Parameter IN StudentArray) IS
BEGIN
NULL;
END PassStudentsI;
PROCEDURE PassStudents2(p_Parameter IN OUT StudentArray) IS
BEGIN
NULL;
END PassStudents2;
PROCEDURE PassStudents3(p_Parameter IN OUT NOCOPY StudentArray) IS
BEGIN
NULL;
END PassStudentsS;
PROCEDURE Go IS

v_StudentArray StudentArray := StudentArray(NULL);


v_StudentRec students%ROWTYPE;
v_Time1 NUMBER;
v_Time2 NUMBER;
v_Time3 NUMBER;
v_Time4 NUMBER;
BEGIN
-- 50001 David Dinsmore,
SELECT *
INTO v_StudentArray(1)
FROM students
WHERE ID = 10007;
v_StudentArray.EXTEND(50000, 1);
- PassStudents .
- DBMS_UTILITY.GET_TIME (
-- ).
v_Time1 := DBMS_UTILITY.GET_TIME;
PassStudentsI(v_StudentArray);
v_Time2 := DBMSJJTILITY.GETJIME;
PassStudents2(v_StudentArray);
v_Time3 := DBMS_UTILITY.GET_TIME;
PassStudents3(v_StudentArray);
v_Time4 := DBMS_UTILITY.GET_TIME;
- .
DBMS_OUTPUT.PUT_LINE('Time to pass IN: ' ||
TO_CHAR((v_Time2 - v_Time1) / 100));
DBMS_OUTPUT.PUT_LINE('Time to pass IN OUT: ' |
TO_CHAR((v_Time3 - v_Time2) / 1 0 0 ) ) ;
DBMS_OUTPUT.PUT_LINE('Time to pass IN OUT NOCOPY: ' | |

331

332

TO_CHAR((v_Time4 - v_Time3) / 100));

END Go;
END CopyFast;
'


.
"", EXTEND
8, a DBMSJJTILITY .

PassStudents , PL/SQL- . 50001 , .. .


, PassStudentsI
IN, PassStudents2 - IN OUT, a PassStudentsS - IN OUT NOCOPY.
, PassStudents2 , . Copy Fast. Go:
)

SQL> BEGIN
2
CopyFast.Go;
3 END;
4 /
Time to pass IN: 0
Time to pass IN OUT: 4 . 2 8
Time to pass IN OUT NOCOPY: 0
PL/SQL procedure successfully completed.

,
IN OUT , IN IN OUT NOCOPY .


,
, . . :
[_|

- noparams.sql
CREATE OR REPLACE PROCEDURE NoParamsP AS
BEGIN
DBMS_OUTPUT.PUT_LINE('No P a r a m e t e r s ! ' ) ;
END NoParamsP;
CREATE OR REPLACE FUNCTION NoParamsF
RETURN DATE AS
BEGIN
RETURN SYSDATE;
END NoParamsF;
BEGIN
NoParamsP;

333

DBMS_OUTPUT.PUT_LINE('Calling NoParamsF on ' ||


TO_CHAR(NoParamsF, ' D D - M O N - Y Y Y Y ' ) ) ;
END;

CALL, Oracle8\,
.


.
) -- CallMe.sql
CREATE OR REPLACE PROCEDURE CallMe (
p_ParameterA VARCHAR2,
p_ParameterB NUMBER,
p_ParameterC BOOLEAN,
p_ParameterD DATE) AS
BEGIN
NULL;
END CallMe;

Q - CallMe.sql
DECLARE
v_Variable1 VARCHAR2(10);
v._Variable2 NUMBER(7,6);
v_Variable3 BOOLEAN;
v_Variable4 DATE;
BEGIN
CallMe(v_Variable1, v_Variable2, v_Variable3, v_Variable4);
END;

,
: v_Variable1 p_ParameterA, v_Variable2 p_ParameterB ..
(positional notation). , , .
(named notation):
Q CallMe.sql
DECLARE
v_Variable1 VARCHAR2(10);
v_Variable2 NUMBER(7,6);
v_Variables BOOLEAN;
v._Vanable4 DATE;
BEGIN
CallMe(p_ParanteterA => v_Variable1,
p_ParameterB => v_Variable2,

334

p_ParameterC => v_Variable3,


p_ParameterD => v_Variable4);

END;


, .
. , CallMe :
Q CallMe.sql
DECLARE

v_Variable1 VARCHAR2(10);
v_Variable2 NUMBER(7,6);
v_Variable3 BOOLEAN;
v_Variable4 DATE;
BEGIN
CallMe(p_ParameterB => v_Variable2,
p_ParameterC => v_Variable3,
p_ParameterD => v_Variable4,
p_ParameterA => v_Variable1);
END;

, . , .
:
Q CallHe.sql
DECLARE

v_Variable1 VARCHAR2(10);
v_Variable2 NUMBER(7,6);
v_Variables BOOLEAN;
v_Variable4 DATE;
BEGIN
- 2 , 2 - .
CallMe(v_Variable1, v_Variable2,
p_ParameterC => v_Variable3,
p_ParameterD => v_Variable4);
END;

PL/SQL, Ada.
, ? , ,
.
, 9.3.
, , ,
.
( ), ,
,

335


. , (. ).

,
.

,
, .
,
(, , PL/SQL,
). PL/SQL
.
9.3.


,
,
.
,

,
,
;
.

, ;
.
, .
, ,
.
,

,
.
,
.


,
.
, . , .
:
_ [] _
{:= | DEFAULT} _

336

_ ,
(IN, OUT IN OUT), _ ( , ), _ , .
:= DEFAULT. AddNewStudent, "" (
):
Q default.sql
CREATE OR REPLACE PROCEDURE AddNewStudent (
p_FirstName students.first_name%TYPE,
p_LastName students.last_name%TYPE,
p_Major
students.major%TYPE DEFAULT 'Economics') AS
BEGIN
- students.
- student_sequence ,
- , 0
-- current_credits.
INSERT INTO students VALUES (student_sequence.nextval,
p_FirstName, p_LastName, p_Major, 0);
END AddNewStudent;

p_Major
, .
:
] default.sql
BEGIN
AddNewStudent('Simon', 'Salovitz');
END;

:
rj ..- default.sql
BEGIN
AddNewStudent(p_FirstName => 'Veronica',
p_LastName => 'Vassily');
END;

,
,
, .
:
| - DefaultTest. sql
CREATE OR REPLACE PROCEDURE DefaultTest (
p_ParameterA NUMBER DEFAULT 10,
p_ParameterB VARCHAR2 DEFAULT 'abcdef ,
p_ParameterC DATE DEFAULT SYSDATE) AS
BEGIN
DBMS_OUTPUT.PUT_LINE(

337

' : ' || p_ParameterA 1 1


' : ' || p_ParameterB 1 1
1
: ' || TO_CHAR(p_ParameterC, ' D D - M O N - Y Y Y Y ' ) ) ;
END DefaultTest;

DefaultTest , .
p_ParameterB, p_ParameterA p_ParameterC
, :
| DefaultTest.sql
SQL> BEGIN
2
DefaultTest(p_ParameterA => 7, p_ParameterC => '30-DEC-95');
3 END;
4 /
A: 7 B: abcdef C: 30-DEC-1995
PL/SQL procedure succefully completed.


p_ParameterB ,
p_ParameterC .
, ,
. :

) -- DefaultTest.sql
SQL> BEGIN

-
- p_ParameterB, p_ParameterC.

4
DefaultTest(7);
5 END;
6 /
: 7 : abcdef : 17--1999
PL/SQL procedure succefully completed.

,
.
, .

CALL
OracleS t SQL : CALL. PL/SQL Java PL/SQL :
CALL _([1_^]) [INTO _\\
_
,

338

. _ , _
. SQL*Plus CALL:
- calls.sql
SQL> CREATE OR REPLACE PROCEDURE CallProd (p1 IN VARCHAR2 := NULL) AS

2
3
4

BEGIN
DBMS_OUTPUT.PUT_LINE('CallProc1 called with ' || p1);
END CallProd;

5 /
Procedure created.
SQL>
2
3
4
5

CREATE OR REPLACE PROCEDURE CallProc2 (p1 IN OUT VARCHAR2) AS


BEGIN
DBMS_OUTPUT.PUT_LINECCallProc2 called with' ||p1);
p1 := p1 || ' returned!';
END CallProc2;

6 /
Procedure created.
SQL>
2
3
4
5

CREATE OR REPLACE FUNCTION CallFunc(p1 IN VARCHAR2)


RETURN VARCHAR2 AS
BEGIN
DBMS_OUTPUT.PUT_LINECCallFunc called with ' || p1);
RETURN p1;

6 END CallFunc;

7 /
Function created

SQL> - SQL
SQL> CALL CallProd('Hello!');
CallProd called with Hello!
Call completed.
SQL> CALL CallProcK);
CallProd called with
Call completed.
SQL> VARIABLE v_0utput VARCHAR2(50);
SQL> CALL CallFuncCHello!') INTO :v_0utput;
CallFunc called with Hello!
Call completed.
SQL> PRINT v_0utput
V_OUTPUT
Hello!
SQL> CALL CallProc2(:v_Output);
CallProc2 called with Hello!
Call completed.

339

SQL> PRINT v_0utput


V_OUTPUT
Hello! returned!
SQL --
SQL> BEGIN
2 CALL CallProcK);
3 END;
4 /

CALL CallProcK):
ERROR at line 2
ORA-06550: line 2, column 8:
PLS-00103: Encountered the symbol "CALLPROC1" when expecting one of the
following:
The symbol "-:=" was substituted for "CALLPROC1" to continue.
SQL> --
SQL> DECLARE
2
v_Result VARCHAR2(50);
3 BEGIN
4
EXECUTE IMMEDIATE 'CALL CallProcK "Hello from PL/SQL")';
5
EXECUTE IMMEDIATE
6
'Call CallFuncC 'Hello from PL/SQL'') INTO :v_Result'
7
USING OUT v_Result;
8 END;
9/
CallFunc called with Hello from PL/SQL
CallProc called with Hello from PL/SQL
PL/SQL procedure sucessfully completed.
, :
CALL SQL.
PL/SQL, SQL (. 12). ( PL/SQL PL/SQL.)
, (
).
INTO . IN OUT OUT
.

SQL *Plus 8.1 CALL


SQL.
SQL* Plus EXECUTE (. 2).

340


:
, OUT.
,
.
.
.
NOCOPY ( OracleS ).
, ?
,
. : ,
, .
OUT (.. ), .
SQL- (. 10).

(package) , PL/SQL Ada. PL/SQL, .


: . .
,
,
. ,
, , ,
, , .
, ,
(. 10).
, . , ,
: , , , .
,
PL/SQL, PL/SQL (
).


, , (package specification),
(package header), , .
:

341

Q -- ClassPackage.sql
CREATE OR REPLACE PACKAGE ClassPackage AS
- .
PROCEDURE AddStudent(p_StudentID IN students.id%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE);
- .
PROCEDURE RemoveStudent( p_StudentID IN students.id%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE);
- , RemoveStudent.
e_StudentNotRegistered EXCEPTION;
- , .
TYPE t_StudentIDTable IS TABLE OF students. id%TYPE
INDEX BY BINARY_INTEGER;
- PL/SQL ,
- .
PROCEDURE ClassList(p_Department
IN classes.department%TYPE,
p_Course
IN classes.course%TYPE,
p_IDs
OUT t_StudentIDTable,
p_NumStudents IN OUT BINARY_INTEGER);
END ClassPackage;

ClassPackage ,
. :
CREATE [OR REPLACE] PACKAGE _ {IS | AS}
_ \
_, \
_, \
_ \
__ \
_ \
_
END [_];
( , ..)
, . ,
, . :
. ,
, ,
. , WHERE ,
.

342

, . ,
.
. (forward declaration) ( ),
(. 10).
, , . .


(package body) , . , .
, .
,
, . ClassPackage :
Q - ClassPackage.sql
CREATE OR REPLACE PACKAGE BODY ClassPackage AS
-- .
PROCEDURE AddStudent(p_StudentID IN students.id%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE) IS
BEGIN
INSERT INTO registered_students (student_id, department., course)
VALUES (p_StudentID, p_Department, p_Course);
END AddStudent;
- .
PROCEDURE RemoveStudent( p_StudetitID IN students. id%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE) IS
BEGIN
DELETE FROM registered_students
WHERE student_id = p_StudentID
AND department = p_Department
AND course = p_Course;
- , DELETE.
- , .
IF SQL%NOTFOUND THEN
RAISE e_StudentNotRegistered;
END IF;
END RemoveStudent;

343

- PL/SQL ,
- .
PROCEDURE ClassList(pJ)epartment
IN classes.department%TYPE,
p_Course
IN classes.course%TYPE,
p_IDs
OUT t_StudentIDTable,
p_NumStudents IN OUT BINARY_INTEGER) IS
v_StudentID registered_students.student_id%TYPE;
- .
CURSOR c_RegisteredStudents IS
SELECT student_id
FROM registered_students
WHERE department = p_Department
AND course = p_Course;
BEGIN
/* p_NumStudents - .
0 .

, .. , p_IDs. */
p_NumStudents := 0;
OPEN c_RegisteredStudents;
LOOP
FETCH c_RegisteredStudents INTO v_StudentID;
EXIT WHEN c_RegisteredStudents%NOTFOUND;
p_NumStudents := p_NumStudents + 1;
p_IDs(p_NumStudents) := v_StudentID;
END LOOP;
END ClassList;
END ClassPackage;


, , , , .
, (,
e _ S t u d e n t N o t R e g i s t e r e d ) ,
.
.
- ( , , ..), .
, (
).

.
,
. , ,
FunctionA, , .

344

rj -- packageError.sql
CREATE OR REPLACE PACKAGE PackageA AS
FUNCTION FunctionA(p_Parameter1 IN NUMBER,
p_Parameter2 IN DATE)
RETURN VARCHAR2;
END PackageA;
CREATE OR REPLACE PACKAGE BODY PackageA AS
FUNCTION FunctionA(p_Parameter1 IN CHAR)
RETURN VARCHAR2;
END PackageA;

P a c k a g e A ,
:
]

PLS-00328: A subprogram body must be defined for the forward


declaration of FUNCTIONA.
( ,
FUNCTIONA)
PLS-00323:

subprogram or cursor 'FUNCTIONA' is declared in a


package specification and must be defined in the package body,
( ()
)


, , .
. , ClassPackage. RemoveStudent
PL/SQL:
Q BEGIN
ClassPackage.RemoveStudent(10006, 'HIS', 101);
END;

,
. .
, , , .. ,
.
, ,
. , ClassList, ClassPackage. t_StudentIDTable (. 8):
Q callCL.sql
DECLARE
v_HistoryStudents ClassPackage. t_StudentIDTable;
v_NumStudents
BINARY_INTEGER := 20;
BEGIN
- PL/SQL 20 History 101.

345

ClassPackage.ClassList('HIS', 101, v_HistoryStudents,


v_NumStudents);
- temp_table.
FOR v_LoopCounter IN 1.. v_NumStudents LOOP
INSERT INTO temp_table (num_col, char_col)
VALUES
(v_HistoryStudents(v_LoopCounter),
'In History 101');
END LOOP;
END;

, ,
. , RemoveStudent
e_StudentNotRegistered,
ClassPackage.e_StudentNotRegistered.
.
,
, ClassPackage.AddStudent ClassPackage.RemoveStudent
registered_students, . ( ) , students classes.
:
3 "~ ClassPackage2.sql
CREATE OR REPLACE PACKAGE BODY ClassPackage AS
- , students classes
- . p_Add ,
- , - .

PROCEDURE UpdateStudentsAndClasses(
p_Add
IN BOOLEAN,
p_StudentID
IN students.idXTYPE,
p_Department
IN classes.departmentXTYPE,
p_Course
IN classes.courseXTYPE) IS
- .
v_NumCredits classes. num_credits%TYPE;
BEGIN
- NumCredits.
SELECT num_credits
INTO v_NumCredits
FROM classes
WHERE department = p_Department
AND course = p_Course;
IF (p_Add) THEN
-- NumCredits .
UPDATE STUDENTS
SET current_credits = current_credits + v_NumCredits
WHERE ID = p_StudentID;

346

9
- current_students.
UPDATE classes
SET current_students = current_students + 1
WHERE department = p_Department
AND course = p_Course;
ELSE
- NumCredits .
UPDATE STUDENTS
SET current_credits = current_credits - v_NumCredits
WHERE ID = p_StudentID;
- current_students.
UPDATE classes
SET current_students = current_students - 1
WHERE department = p_Department
AND course = p_Course;
END IF;
END UpdateStudentsAndClasses;
- .
PROCEDURE AddStudent(p_StudentID IN students.id%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE) IS
BEGIN
INSERT INTO registered_students (student_id, department, course)
VALUES (p_StudentIO, p_Department, p_Course);
UpdateStudentsAndClasses(TRUE, p_StudentID, p_Department,
p_Course);
END AddStudent;
- .
PROCEDURE RemoveStudent(p_StudentID IN students.id%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE) IS
BEGIN
DELETE FROM registered_students
WHERE student_id = p_StudentID
AND department = p_Department
AND course = p_Course;
- , DELETE.
- , .
IF SQL%NOTFOUND THEN
RAISE e_StudentNotRegistered;
ND IF;
UpdateStudentsAndClasses(FALSE, p_StudentID, p_0epartment,
p_Course);
END RemoveStudent;
END ClassPackage;

347

UpdateStudentsAndClasses , , , . , (
AddStudent RemoveStudent), .


(overloaded).
,
, . ,

. , , ,
. , ClassPackage :
Q overload.sql
CREATE OR REPLACE PACKAGE ClassPackage AS
- .
PROCEDURE AddStudent(p_StudentID IN students.id%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE);
- ,
- , .
PROCEDURE AddStudent(p_FirstName IN students.first_name%TYPE,
p_LastName
IN students. last_name%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE);
END ClassPackage;
CREATE OR REPLACE PACKAGE BODY ClassPackage AS
- .
PROCEDURE AddStudent(p_StudentID IN students.id%TYPE,
p_Department IN classes.department%TYPE,
p_Course IN classes.course%TYPE) IS
BEGIN
INSERT INTO registered_students (student_id, department, course)
VALUES (p_StudentID, p_Department, p_Course);
END AddStudent;
- , .
PROCEDURE AddStudent(p_FirstName IN students.first_name%TYPE,
p_LastName
IN students.last_name%TYPE,
p_Department IN classes.department%TYPE,
p_Course
IN classes.course%TYPE) IS
v_StudentID students. id%TYPE;
BEGIN
/* students. */
SELECT ID
INTO v StudentID

348

FROM students
WHERE first_name = p_FirstName

AND last_name = p_LastName;

- .
INSERT INTO registered_students (student_id, department, course)
VALUES (v_StudentID, p_Department, p_Course);
END AddStudent;
END ClassPackage;

Music 410 :
Q BEGIN

ClassPackage,AddStudent(10000, 'MUS', 410);


END;

:
(_J BEGIN
ClassPackage.AddStudent('Rita', 'Razmataz', 'MUS', 410);
END;
,
. :
, . , :
PROCEDURE OverloadMe(p_TheParameter IN NUMBER);
PROCEDURE OverloadMe(p_TheParameter OUT NUMBER);

, . , :
FUNCTION OverloadMeToo RETURN DATE;
FUNCTION OverloadMeToo RETURN NUMBER;

, . , CHAR
VARCHAR2 ,
:
PROCEDURE OverloadChar(p_TheParameter IN CHAR);
PROCEDURE OverloadChar(p_TheParameter IN VARCHAR2);

349

PL/SQL
, ,
.


PLS-307: Too many declarations of '' match this call
(
'').


OracleB/ 1
I . ,
:
Q - objectOverload.sql
CREATE OR REPLACE TYPE t1 AS OBJECT (
f NUMBER

);
CREATE OR REPLACE TYPE t2 AS OBJECT (
f NUMBER

, ,
:
)

objectOverload.sql
CREATE OR REPLACE PACKAGE Overload AS
PROCEDURE Proc(p_Parameter1 IN t1);
PROCEDURE Proc(p_Parameter1 IN t2);
END Overload;
CREATE OR REPLACE PACKAGE BODY Overload AS
PROCEDURE Proc(p_.Parameter1 IN t1) IS
BEGIN
DBMS_OUTPUT.PUT_LINECProc(t1): ' || p_Parameter1 . f );
END Proc;
PROCEDURE Proc(p_Parameter1 IN t2) IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Proc(t2): ' || p_Parameter1 . f );
END Proc;
END Overload;
, :

objectOverload.sql
SQL> DECLARE
2
v_0b]1 t1 := t1(1);
3
v_0b]2 t2 := t2(2);

350

BEGIN

5
Overload.Proc(v_0bj1);
6
Overload.Proc(v_0bj2);
7 END;
8 /
Proc(t1): 1
Proc(t2): 2
PL/SQL procedure succefully completed.
12 13.


(instantiated). ,
, . , , .
; , , , .
.
, :
CREATE OR REPLACE PACKAGE BODY _ (IS | AS}
BEGIN
_,,;
END [_];
__ , _, .
, .
| -- Random.sql
CREATE OR REPLACE PACKAGE Random AS
- . ,
-- rand() .
-- (seed).
-
- .
PROCEDURE ChangeSeed(p_NewSeed IN NUMBER);
- 1 32767.
FUNCTION Rand RETURN NUMBER;
- Rand, .
PROCEDURE GetRand(p_RandomNumber OUT NUMBER);
- 1 p_MaxVal.

351

FUNCTION RandMax(p_MaxVal IN NUMBER) RETURN NUMBER;


- RandMax, .
PROCEDURE GetRandMax(p_RandomNumberOUT NUMBER,
p_MaxVal IN NUMBER);
END Random;
CREATE OR REPLACE PACKAGE BODY Random AS
/* .
v_Multiplier CONSTANT NUMBER := 22695477;
v_Increment CONSTANT NUMBER := 1;

*/

/*

,
. */
v_Seed
number := 1;
PROCEDURE ChangeSeed(p_NewSeed IN NUMBER) IS
BEGIN
v_Seed := p_NewSeed;
END ChangeSeed;
FUNCTION Rand RETURN NUMBER IS
BEGIN
v_Seed := MOD(v_Multiplier * v_Seed + v_Increment,
(2 ** 32));
RETURN BITAND(v_Seed/(2 ** 16), 32767);
END Rand;
PROCEDURE GetRand(p_RandomNumberOUT NUMBER) IS
BEGIN
- Rand .
p_RandomNumber := Rand;
END GetRand;

FUNCTION RandMax(p_MaxVal IN NUMBER) RETURN NUMBER IS


BEGIN
RETURN MOD(Rand, p_MaxVal) + 1;
END RandMax;
PROCEDURE GetRandMax(p_RandoinNumber OUT NUMBER,
p_MaxVal IN NUMBER) IS
BEGIN
- RandMax .
p_RandomNumber := RandMax(p_MaxVal);
END GetRandMax;
BEGIN
/* .
. */
ChangeSeed(TO_NUMBER(TO_CHAR(SYSDATE, 'SSSSS')));
END Random;

352

Random. Rand.
:
. , ,
. ChangeSeea.

OracleS DBMS_RANDOM,

(. ).

PL/SQL :
, .
, . ,
. ,
SQL-.
11
.

10

354

10

,
. ,
,
SQL-. OracleSz 19. 11
.


.
CREATE OR REPLACE, PL/SQL. ,
; (local subprogram).
.


CREATE OR
REPLACE, ,
, ,
- (p-code). - , ,
PL/SQL. -
. - (SGA), .
, - LRU.
- , , - Java,
Java. -
( ), -
() .

'

Oracle9\
, - (. ).

. user_objects
, ,
. ,
,

355

(, , ..),
. user_source , u s e r _ e r r o r s
.
:
Q

CREATE OR REPLACE PROCEDURE Simple AS


v_Counter NUMBER;
BEGIN
v_Counter := 7;
END Simple;

user_objects , (valid), user_source . user_errors ,


(. 10.1).
9. Oracle SQL-Plus
File

Edit

Search

Options

Help

SQL> SELECT object_name, object_type, status


2
FROM user_objects WHERE object_name = 'SIMPLE';
OBJECT_NftME

OBJECT_TVPE

STATUS

SIMPLE

PROCEDURE

UALID

_*j

SQL> SELECT text FROM user_source


2
WHERE name = 'SIMPLE 1 ORDER BV line;
TEXT
PROCEDURE Simple AS
u_Counter NUMBER;
BEGIN

u_Counter := 7;
END Simple;

SQL> SELECT line, position, text


2
FROM user_errors
3
WHERE name = 'SIMPLE'
4
ORDER BV sequence;
no rows selected
SQL>

. 10.1.
Simple ,
( ):
CREATE OR REPLACE PROCEDURE Simple AS
v_Counter NUMBER;
BEGIN

356

10

v_Counter := 7
END Simple;

(. 10.2).
user_source - , user_objects INVALID (),
a u s e r _ e r r o r s PLS-103.
ft Oracle SQL-Plus
Ffe Edit ieatch flptions Help
SQL> SELECT object_name, object_type, status
2
FROM user_objects WHERE object_narae - 'SIMPLE';
OBJECT_NAME

OBJECT_TVPE

SIMPLE

PROCEDURE

STATUS
INUALID

sqL> SELECT text FROM user_source


2
WHERE name - 'SIMPLE* ORDER BY line;
TEXT
PROCEDURE Simple AS
u_Counter NUMBER;
BEGIN
u_Counter :- 7
END Simple;
SQL> SELECT line, position, text

FROM user_errors

3
1

WHERE name - 'SIMPLE'


ORDER BY sequence;
LINE

POSITION TEXT
1 PLS-00103: Encountered the symbol "END" when expecting one OF
the following:
6 - - + ; < / > i n nod not rem an exponent ()
<> or != or ~- >- <- <> and or like between is null is not

II

is dangling
The symbol ";" was substituted For "END" to continue.

..

|
i

+M

. 10.2.
/

SQL*Plus user_errors
SHOW
ERRORS ( ).
.
SHOW ERRORS "Warning:
Procedure created with compilation errors"(!
.).
2.
. .
PLS-905:

357

) SQL> BEGIN Simple; END;


2 /
BEGIN Simple; END;

ERROR at line 1:

ORA-06550: line 1, column 7:


PLS-00905: object EXAMPLE.SIMPLE is invalid
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
.

- Java, -
PL/SQL. ,
PL/SQL , , . - - , , ,
.
19 PL/SQL- .
, Oracle
. . PL/SQL-
, .

Oracle.


,
PL/SQL, :
] -- localSub.sql
SQL> DECLARE
2
CURSOR c_AHStudents IS
3
SELECT first_name, last_name
4
FROM students;
5
6
v_FormattedName VARCHAR2(50);
7
8
/* ()
9
, . */
10 FUNCTION FormatName(p_FirstName IN VARCHAR2,
11
p_LastName IN VARCHAR2)
12

RETURN VARCHAR2 IS

13 BEGIN
14
RETURN p_FirstName I I ' ' I I p_LastName;
15 END FormatName;
16
17 -- .

358

10

18

BEGIN

19
20
21
22
23

FOR v_StudentRecord IN c_AHStudents LOOP


v_FormattedName :FormatName(v_StudentRecord. first_name,
v_StudentRecord. last_name);
OBMS_OUTPUT,PUT_LINE (v_FormattedName);

24

END LOOP;

25

END;

26

Scott Smith
Margaret Mason
Joanne Junebug
Manish Murgatroid
Patrick Poll
Timothy Taller
Barbara Blues
David Dinsmore
Ester Elegant
Rose Riznit
Rita Razmataz
Shay Shariatpanahy
PL/SQL procedure succesfully completed.
FormatName . PL/SQL
,
PL/SQL. , , ,
. FormatName ,
.


, .
FormatName StoredProc, :
) localStored.sql
CREATE OR REPLACE PROCEDURE StoredProc AS
/* , */
CURSOR c.AHStudents IS
SELECT first_name, last_name
FROM students;
v_FormattedName VARCHAR2(50);
/* ,
. */

FUNCTION FormatName(p_FirstName IN VARCHAR2,


p_LastName IN VARCHAR2)
RETURN VARCHAR2 IS

359

BEGIN

RETURN p_FirstName || ' ' II p_LastName;


END FormatName;
-
BEGIN
FOR v_StudentRecord IN c_AllStudents LOOP
v_FormattedName :=
FormatName(v_StudentRecord.first_name,
v_StudentRecord.last_name);
DBMS_OUTPUT.PUT_LINE(v_FormattedName);
END LOOP;
END StoredProc;
, ,
:
-- localStored.sql
SQL> BEGIN
2
StoredProc;
3 END;
4 /
Scott Smith
Margaret Mason
Joanne Junebug
Manish Murgatroid
Patrick Poll
Timothy Taller
Barbara Blues
David Dinsmore
Ester Elegant
Rose Riznit
Rita Razmataz
Shay Shariatpanahy
PL/SQL procedure succesfully completed.


. FormatName c_AHSturjerits, :
- localError.sql
SQL> DECLARE
2
/* FormatName.
3
,
4
. */
5
FUNCTION FormatName(p_FirstName IN VARCHAR2,
6
p_LastName IN VARCHAR2)
7
RETURN VARCHAR2 IS
8
BEGIN
9
RETURN p_FirstName | ' ' |l P.LastName;

360

10

10 ND FormatName;
11

12 CURSOR c_AHStudents IS
13
SELECT first_name, last_name
14
FROM students;
15
16 v_FormattedName VARCHAR2(50);
17 - .
18 BEGIN
19
NULL;
20 END;
21 /
CURSOR c_AHStudents IS

ERROR at line 12:


ORA-06550: line 12, column 3:
PLS-00103: Encountered the symbol "CURSOR" when expecting one of the
following;
begin function package pragma procedure form


PL/SQL ,
.
, ,
. :
Q - mutual.sql
SQL> DECLARE

2
3
4
5
6
8
9
10
11
12
13
14
15
16

v_TempVal BINARY_INTEGER := 5;
- . ,
- .
PROCEDURE A(p_Counter IN OUT BINARY_INTEGER) IS
BEGIN
DBMS_OUTPUT.PUT_LINE('AC || p_Counter || ')');
IF p_Counter > 0 THEN
B(p_Counter);
p_Counter ;= p_Counter - 1;
END IF;
END A;
- . ,
- .
PROCEDURE B(p_Counter IN OUT BINARY_INTEGER) IS
BEGIN

DBMS_OUTPUT.PUT_LINECBC || p_Counter |
18
p_Counter := p_Counter - 1;
19
A(p_Counter);
20
END B;
21 BEGIN
22
B(v_TempVal);
23 END;

361

24 /
DECLARE
'

ERROR at line 1:
ORA-06550: line 9, column 7:
PLS-00201: identifier 'B' must be declared
ORA-06550: line 9, column 7:
PL/SQL: Statement ignored
.
, .
, . .
, (forward declaration),
. , . . :
Q - forwardDeclaration.sql
DECLARE

vJempVal BINARY_INTEGER := 5;

- .
PROCEDURE B(p_Counter IN OUT BINARY_INTEGER);
PROCEDURE A(p_Counter IN OUT BINARY_INTEGER) IS
BEGIN
DBMS_OUTPUT.PUT_LINE('AC || p_Counter || ' )')';IF p_Counter > 0 THEN
B(p_Counter);
p_Counter := p_Counter - 1;
END IF;
END A;
PROCEDURE B(p_Counter IN OUT BINARY_INTEGER) IS
BEGIN
DBMS_OUTPUT.PUT_LINECA(' || p_Counter || ')');
p_Counter := p_Counter - 1;
A(p_Counter);
END B;
BEGIN
B(v_TempVal);
END;
:
(4)
(4)
(3)
(3)

362

10

(2)
(2)

(0)


9, , ,
. , :
]

overloadedLocal.sql
DECLARE
-
PROCEDURE LocalProc(p_Parameter1 IN NUMBER) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(' In version 1, p_Parameter1 = ' |l
p_Parameter1);
END LocalProc;
PROCEDURE LocalProc(p_Parameter1 IN VARCHAR2) IS
BEGIN
DBMS_OUTPUT.PUT_LINE('In version 2, p_Parameter1 = ' II
p_Parameter1);
END LocalProc;
BEGIN
- 1.
LocalProc(12345);
- 2.
LocalProc('abcdef ' );
END;
:

Q In version 1, p_Parameter1 = 12345


In version 2, p_Parameter1 = abcdef


.
?
, . , ,
.
.
, , , (, ). , ,
, .

10.1.

363

10.1.

,
-;
.
.
,
.
,

, ,
EXECUTE
.


, .
. , ,

,
.
-

,
DBMS_SHARED_POOLKEEP.'
.
,
,
( ).
DBMS_SHARED_POOL " ".



. , . , . ,
.


Oracle, , . , (dependent) . ,
, ,
.
, ,
, DDL. .
AlmostFull (. 9) classes.
AlmostFull . 10.3. AlmostFull classes. .

364

10

. 10.3. AlmostFull
, AlmostFull temp_table. RecordFullClasses:
] RecordFullClasses.sql
CREATE OR REPLACE PROCEDURE RecordFullClasses AS
CURSOR c_Classes IS
SELECT department, course
FROM classes;
BEGIN
FOR v_ClassRecord IN c_Classes LOOP
- temp_table ,
- .
IF AlmostFull(v_ClassRecord.department, v_ClassRecord.course)
THEN
INSERT INTO temp_table (char_col) VALUES
(v_ClassRecord.department || ' ' || v_ClassRecord.course ||
' is almost full! ');
END IF;
END LOOP;
END RecordFullClasses;

. 10.4. RecordFullClasses AlmostFull, temp_table. (direct), RecordFullClasses


A l m o s t F u l l temp_table. AlmostFull
classes, RecordFullClasses (indirect) classes.
AlmostFull

classes
RecordFullClasses

tempjtable AlmostFull
classes.

. 10.4. RecordFullClasses

365

classes DDL, ,
classes ( ), . classes, :
ALTER TABLE classes ADD (
student_rating NUMBER(2) -- 1 10

AlmostFull, RecordFullClasses , classes. . 10.5 SQL* Plus.


A. Oracle SQL'Plus
FSe Edit Search Options Help
SQL> SELECT object_nane, object_type, status
2
FROM user_objects
1
1
3
WHERE object_name IN ('flLMOSTFULL , 'RECORDFULLCLASSES );
OBJECT HfiME

OBJECT TYPE

STflTUS

RECORDFULLCLflSSES
ALMOSTFULL

PROCEDURE
FUNCTION

URLID
UALID

SQL> ALTER TflBLE classes ADD

2
student_rating
3 );

NUMBER(Z)

Difficulty rating fron 1 to 10

Table altered.
SQL> SELECT object_nane, object_type, status
2
FROM user_objects
3

WHERE object name IN ("flLMOSTFULL1, 'RECORDFULLCLASSES1);

OBJECT NAME

OBJECT TVPE

STflTUS

RECORDFULLCLASSES
ALMOSTFULL

PROCEDURE
FUNCTION

INVALID
INUALID

SQL>

JLU

. 10.5. DDL


,
PL/SQL
. RecordFullClasses, AlmostFull
classes, (. . 10.6).

366

10

^Oracle SQL-Plus
file Edit Search Options 1
Table altered.
SQL> SELECT odject_name, object_type, status
2
FROM user_objects
1
1
3
WHERE object_nane IN ('flLMOSTFULL , 'RECORDFULLCLflSSES );
OBJECT NAME

OBJECT TYPE

STflTUS

RECORDFULLCLflSSES
BLMOSTFULL

PROCEDURE
FUNCTION

INUflLID
INUALID

SQL> exec RecordFullClasses;


PL/SQL procedure successfully completed.
SQL> SELECT object_narae, object_type, status
2
FROM user_objects
3
WHERE object_name IN flLMOSTFULL', 'RECORDFULLCLflSSES');
OBJECT NAME

OBJECT TVPE

STflTUS

RECORDFULLCLASSES
ALMOSTFULL

PROCEDURE
FUNCTION

UflLID
UflLID

SQL>

J-JJ

. 10.6.

!

( ).
.

, .


, .
. ClassPackage
(. 9), . 10.7.
registered_students . , registered_students. . ,
. , , , .
,
, .

367

ClassPackage
registered_students.

.
registered_students
ClassPackage
,
.
. 10.7. ClassPackage


. ,
, , ,
, ,
.
,
. ,
(.
" ")

,
(, ) .

SQL*Plus:
| - dependencies, sql
SQL> -- .
SQL> CREATE TABLE simple_table (f1 NUMBER);
Table created.
SQL> -- , .
SQL> CREATE OR REPLACE PACKAGE Dependee AS

2 PROCEDURE Example(p_Val IN NUMBER);


3 END Dependee;

4 /

Package created.
SQL> CREATE OR REPLACE PACKAGE BODY Dependee AS
2 PROCEDURE Example(p_Val IN NUMBER) IS
3
BEGIN
4
INSERT INTO slmple_table VALUES (p_Val);
5
END Example;
6 END Dependee;
7 /
Package body created.

368

10

SQL> -- , Dependee.
SQL> CREATE OR REPLACE PROCEDURE Depender(p_Val IN NUMBER) AS
2 BEGIN
3
Dependee.Example(p_Val+ 1);
4 END Depender;

5 /

Procedure created.

SQL> -- user_objects , .
SQL> SELECT object_name, object_type, status
2

FROM user_objects
1

3
WHERE object_name IN ('DEFENDER', ' DEPENDEE ,
4
'SIMPLEJTABLE');
OBJECT NAME
OBJECT TYPE
STATUS

SIMPLE_TABLE
DEPENDEE
DEPENDEE
DEPENDER

TABLE
PACKAGE
PACKAGE BODY
PROCEDURE

VALID
VALID
VALID
VALID

SQL> -- . ,
SQL> -- .
SQL> CREATE OR REPLACE PACKAGE BODY Dependee AS
2 PROCEDURE Example(p_Val IN NUMBER) IS
3
BEGIN
4
INSERT INTO simple_table VALUES (p_Val - 1);
5
END Example;

6 END Dependee;
7 /

Package body created.


SQL> -- user_objects , Depender -
SQL> -- .
SQL> SELECT object_name, object_type, status
2
FROM user_objects
3 WHERE object_name IN ('DEFENDER', 'DEPENDEE',
4 'SIMPLE_TABLE');
OBJECT_NAME
OBJECT_TYPE
SIMPLE_TABLE
DEPENDEE
DEPENDEE
DEPENDER PROCEDURE VALID

TABLE
PACKAGE
PACKAGE BODY

STATUS
VALID
VALID
VALID

SQL> --
SQL> -- .
SQL> DROP TABLE simple_table;

Table dropped.
SQL> SELECT object_name, object_type, status
2
FROM user_.objects

369

3
WHERE object_name IN ('DEFENDER', 'DEPENDEE',
4
SIMPLE_TABLE');
OBJECT,NAME
OBJECT_TYPE
STATUS
DEPENDEE
DEPENDEE
DEPENDER

PACKAGE
PACKAGE BODY
PROCEDURE

VALID
INVALID
VALID

6 user_dependencies,
all_dependencies dba_dependencies
, .

.
. 10.8 ,
.

Dependee.Example
( )

Depender

.

Dependee.Example
( )

simplejtable

simplejtable
.

. 10.8.


. ,
. ,
. , : 1 2 (. 10.9).
1 2, .. 2 1
. SQL*Plus.

370

10

CREATE OR REPLACE PROCEDURE P1 AS


BEGIN
DBMS OUTPUT. PUT LINEC Inside P1!');
P2
END P1;

CREATE OR REPLACE PROCEDURE P2 AS


BEGIN
DBMS OUTPUT. PUT LINEC Inside P2! ');
"END P2;

PL/SQL
. 10.9. P1 2
] ..- remoteDependencies.sql '
SQL> -- . 1 2.
SQL> CREATE OR REPLACE PROCEDURE P2 AS
2 BEGIN
3
DBMS_OUTPUT.PUT_LINECInside P2! ');
4 END P2;

5 /
Procedure created.
SQL> CREATE OR REPLACE PROCEDURE P1 AS
2 BEGIN
3
DBMS_OUTPUT.PUT_LINE('Inside P1! ');
4
P2;
5 ENDP1;
6 /
Procedure created.

SQL> -- .
SQL> SELECT object_name, object_type, status
2
FROM user_objects
3
WHERE object_name IN , - P 2 ' ) ;
OBJECT_NAME
OBJECT_TYPE

STATUS

P2
Pi

VALID
VALID

PROCEDURE
PROCEDURE

SOL> -- 2, 1 .
SQL> ALTER PROCEDURE P2 COMPILE;
Procedure altered.
SQL > -- .
SQL> SELECT object_name, object_type, status
2 FROM user_objects
3 WHERE object_name IN , P2');
OBJECT_NAME
OBJECT TYPE
STATUS
P2
P1

PROCEDURE
PROCEDURE

VALID
INVALID

371

CREATE OR REPLACE PROCEDURE P1 AS


BEGIN
DBMS_OUTPUT. PUT_LINE( ' Inside P1 ! ' ) ;
P2@loopback;

CREATE OR REPLACE PROCEDURE P2 AS


BEGIN
DBMS_OUTPUT.PUT_LINE(' Inside P2! ' ) ;
' END P2;

END P1;

PL/SQL 2

PL/SQL 1
. 10.10. P1 2

, 1 2 , 1
2, (. 10.10).
2 1,
SQL*Plus:
] - remoteDependencies.sql
SQL> -- , .
SQL> -- connect_string
SQL> -- SQL*Net .
SQL> CREATE DATABASE LINK loopback
2
USING 'connect_string';
Database link created.
SQL> -- R1 , 2 .
SQL> CREATE OR REPLACE PROCEDURE P1 AS
2 BEGIN

3 DBMS_OUTPUT.PUT_LINEC Inside P1! ');


4
P2@loopback;
5 END P1;
6

Procedure created.
SQL> -- .
SQL> SELECT object_name, object_type, status
2
FROM user_objects
3
WHERE object_name IN , ' 2 ' ) ;
OBJECT_NAME
OBJECT TYPE STATUS

P2
P1

PROCEDURE
PROCEDURE

VALID
VALID

SQL> - 2 1
SQL> - .
SOL> ALTER PROCEDURE P2 COMPILE;

Procedure altered.
SQL> SELECT object_name, object_type, status

372

10

2
FROM user_pbjects
3
WHERE objectjiame IN C R T , ' P 2 ' ) ;
OBJECT NAME
OBJECT TYPE
STATUS
2
P1

PROCEDURE
PROCEDURE

VALID
VALID


(loopback), ..
. ,
1 2 .

1 2 SELECT.

? , .
,
( ).
. 1
2 ( , ). 1 2 , , 1. :
.


. 1
PL/SQL (,
Oracle Forms), a P2 ,
(. 2).


, . (timestamp) last_ddl_time
user_objects. ,
, .
:
PL/SQL. , .

373


,
. 2 , . 1 , - .
, 1
PL/SQL, Oracle Forms. , 1 ,
Oracle Forms, .
PL/SQL
. . - (signature).
. 2
. 1 , 2 ( ), 1 2.

REMOTE_DEPENDENCIES_MODE SIGNATURE.
( , init. ,
). , .
:

REMOTE_DEPENDENCIES_MODE=SIGNATURE.
SIGNATURE
.
:
ALTER SYSTEM SET REMOTE_DEPENDENCIES_MODE = SIGNATURE;

( ),
. ALTER SYSTEM.
:
ALTER SESSION SET REMOTE_DEPENDENCIES_MODE = SIGNATURE;

. , , .
SIGNATURE
TIMESTAMP, .
TIMESTAMP .
:

374

10

, , . ,
2
, 1.
2, 1 .
, ,
, 1 . IN.
1 2 , 2,
. 1 ( )
, 1 .
,
:
ALTER PROCEDURE _ COMPILE;
_ . :
ALTER FUNCTION _ COMPILE;
:
ALTER PACKAGE _ COMPILE;
ALTER PACKAGE _ COMPILE SPECIFICATION;
ALTER PACKAGE _ COMPILE BODY;
SPECIFICATION, . BODY,
. , ,
.

"Oracle Server Application Developer's Guide".


-
. (runtime state), .. , ,
. ( ) .
, . 9, , , .
PL/SQL, EXECUTE . ,
. :

375

) -- PersistPkg.sql
CREATE OR REPLACE PACKAGE PersistPkg AS
- ,
TYPE t_StudentTable IS TABLE OF students. ID%TYPE
INDEX BY BINARY_INTEGER;
- , .
v_MaxRows NUMBER := 5;
- v_MaxRows .
PROCEDURE ReadStudents(p_StudTable OUT t_StudentTable,
p_NumRows OUT NUMBER);
END PersistPkg;
CREATE OR REPLACE PACKAGE BODY PersistPkg AS
- students .
- , .
CURSOR StudentCursor IS
SELECT ID
FROM students
ORDER BY last_nane;
PROCEDURE ReadStudents(p_StudTable OUT t_StudentTable,
p_NumRows OUT NUMBER) IS
v_Done BOOLEAN := FALSE;
v_NumRows NUMBER := 1;
BEGIN
IF NOT StudentCursor%ISOPEN THEN
- .
OPEN StudentCursor;

END IF;
- , v_MaxRows .
WHILE NOT v_Done LOOP
FETCH StudentCursor INTO p_StudTable(v_NumRows);
IF StudentCursor%NOTFOUNDTHEN
- , .
CLOSE StudentCursor;
v_Done := TRUE;
ELSE
v_NumRows := v_NumRows + 1;
IF v_NumRows > v_MaxRows THEN
v_Done := TRUE;
END IF;
END IF;
END LOOP;
- .
p_NumRows := v_NumRows - 1;
END ReadStudents;
END PersistPkg;

376

10

PersistPkg.ReadStudents
StudentsCursor. ( ReadStudents),
ReadStudents. PersistPkg.ReadStudents :
FJ

callRS.sql
DECLARE

v_StudentTable PersistPkg. t_StudentTable;


v_NumRows NUMBER := PersistPkg.v_MaxRows;
v_FirstName students. first_name%TYPE;
v_LastName students.last_name%TYPE;
BEGIN
PersistPkg,ReadStudents(v_StudentTable, v_NumRows);
DBMS_OUTPUT.PUT_LINE(' Fetched ' [| v_NumRows || ' rows:');
FOR v_Count IN 1.. v_NumRows LOOP
SELECT first_name, last_name
INTO v_FirstName, v_LastName
FROM students
WHERE ID = v_StudentTable(v_Count);
DBMS_OUTPUT.PUT_LINE(v_FirstName 1 1 ' ' |l v_LastName);
END LOOP;
END;
#. Oracle SQL'Plus
File dit Search Options Help

SQL> @cti8S\callRS
Fetched 5 rows:
Barbara Blues
Dauid Dinsmore
Ester Elegant
Joanne Junebug
Margaret Mason
PL/SQL procedure successfully completed.
SQL> @ch05\callRS
Fetched 5 rows:
Manish Murgatroid
Patrick Poll
Rita Raznataz
Rose Riznit
Shay Shariatpanahy
PL/SQL procedure successfully completed.
SQL> @ch05\callRS
Fetched 2 rows:
Scott Smith
Timothy Taller
PL/SQL procedure successfully completed.

JLU
. 10.11. ReadStudents

377


. 10.11. ,
.


PL/SQL . (serially reusable) ,
.
PRAGMA SERIALLY_REUSABLE;
( ). PersistPkg, (.
. 10.12).
-- PersistPkg2.sql
CREATE OR REPLACE PACKAGE PersistPkg AS
PRAGMA SERIALLY_REUSABLE;
- ,
TYPE t StudentTable IS TABLE OF students. ID%TYPE
..Oracle SQL-Plus
File Edit Search flptiom Help
SQL> GchOS\callRS
Fetched 5 rows:
Barbara Blues
Dauid Dinsmore
Ester Elegant
Joanne Junebug
Margaret Mason

PL/SQL procedure successfully completed.


SQL> <2ch8S\callRS
Fetched 5 rows:
Barbara Blues
Dauid Dinsmore
Ester Elegant
Joanne Junebug
Margaret Mason
PL/SQL procedure successfully completed.
SQL> @ch85\callRS
Fetched 5 rows:
Barbara Blues
Dauid Dinsmore
Ester Elegant
Joanne Junebug
Margaret Mason
PL/SQL procedure successfully completed.

. 10.12. ReadStudents

378

10
INDEX BY BINARY_INTEGER;
- , .
v_MaxRows NUMBER := 5;
- v_MaxRows .
PROCEDURE ReadStudents(p_StudTableOUT t_StudentTable,
p_NumRows OUT NUMBER);
END PersistPkg;
CREATE OR REPLACE PACKAGE BODY PersistPkg AS
PRAGMA SERIALLY_REUSABLE;
- students .
- ,
- , .
CURSOR StudentCursor IS
SELECT ID
FROM students
ORDER BY last_name;
END PersistPkg;

, (, , ) .
.
, .



,
.




, , ,
.


, .
:
Q - anonymousDependencies.sql
CREATE OR REPLACE PACKAGE SimplePkg AS

379

v_GlobalVar NUMBER := 1;
PROCEDURE UpdateVar;
END SimplePkg;
CREATE OR REPLACE PACKAGE BODY SimplePkg AS
PROCEDURE UpdateVar IS
BEGIN
v_GlobalVar := 7;
END UpdateVar;
END SimplePkg;

SimplePkg v_GlobalVar.
, SimplePkg . SimplePkg. UpdateVar :
Q

BEGIN

SimplePkg.UpdateVar;
END;

SimplePkg ,
. . :
]

BEGIN
*

ERROR at line 1:
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package "EXAMPLE. SIMPLEPKG" has been
invalidated
ORA-04065: not executed, altered or dropped package
"EXAMPLE.SIMPLEPKG"

ORA-06508: PL/SQL: could not find program unit being called


ORA-06512: at line 2
( .
EXAMPLE.SIMPLEPKG . ,
EXAMPLE.SIMPLEPKG. .)
? . 10.13. SimplePkg ,
. ,
. , .
, SimplePkg
,
ORA-4068.
: .
, .

380

10

SimplePkg
v_GlobalVar
.
. 10.13.


,

. ,
.
, ,
.
EXECUTE
,
SELECT, INSERT, UPDATE DELETE.
GRANT.
EXECUTE.
RecordFullClasses:
Q execute.sql
CREATE OR REPLACE PROCEDURE RecordFullClasses AS
CURSOR c_Classes IS
SELECT department, course
FROM classes;
BEGIN
FOR v_ClassRecord IN c_Classes LOOP
- temp_table ,
- .
IF AlmostFull(v_ClassRecord.department, v_ClassRecord.course) THEN
INSERT INTO temp_table (char_col) VALUES
(v_ClassRecord.department 1 1 ' ' 1 1 v_ClassRecord.course
1 1 ' is almost full! ');
END IF;
END LOOP;
END RecordFullClasses;

381

execute, sql UserA UserB,


, .
, ,
DBA.
execute, sql execute, out,

, , RecordFullClasses ( AlmostFull classes temp_table),


UserA. RecordFullClasses. EXECUTE RecordFullClasses
, , UserB:
] - execute.sql
GRANT EXECUTE ON RecordFullClasses TO UserB;

UserB RecordFullClasses ( ):
[_) - execute.sql
BEGIN
UserA.RecordFullClasses;
END;

UserA (. . 10.14).
( GRANT) UserA UserB, ,
.
UserA.temp_table.

. 1!

classes

UserA

UserB


UserA.temp_table
. 10.14. UserA

382

10

__ _ _ _ _ , W

RecordFullClasses

AlmostFull
1

classes

temp_table

User A


UserA.temp_table.

UserB

UserB.temp_table
.

. 10.15. UserA UserB


temp_table

, UserB , tempjtable (. 10.15). UserB UserA. RecordFullClasses


( ), ? U s e r A .
:
.
UserB RecordFullClasses, UserA.
temp_table , UserA, UserB.
OracleSi , " ". : (. "
").


, . 10.15. , UserA temp_table, RecordFullClasses,
UserB. , RecordFullClasses , UserA (. . 10.16).
- execute.sql
CREATE OR REPLACE PROCEDURE RecordFullClasses AS
CURSOR c_Classes IS
SELECT department, course

383


UserB.temp_table.
. 10.16.

UserB

RecordFullClasses

FROM UserA. classes;


BEGIN
FOR v_ClassRecord IN c_Classes LOOP
- temp_table ,
- .
IF UserA.AlmostFull(v_ClassRecord.department,
v_ClassRec.ord.course) THEN
INSERT INTO temp_table (char_col) VALUES
(v_ClassRecord.department 1 1 ' ' 1 1 v_ClassRecord.course 1 1
' is almost full! ');
END IF;
END LOOP;
END RecordFullClasses;

RecordFullClasses , UserA SELECT


classes EXECUTE AlmostFull UserB (. . 10.16). ,
, . GRANT,
UserA UserB.RecordFullClasses.

) execute.sql
GRANT SELECT ON classes TO UserB;
GRANT EXECUTE ON AlmostFull TO UserB;

:
FJ -- execute, sql

384

10

CREATE ROLE UserA_Role;


GRANT SELECT ON classes TO UserA_Role;
GRANT EXECUTE ON AlmostFull TO UserA_Role;
GRANT UserA_Role TO UserB;

.
. 10.17.

UserB.RecordFullClasses
,

.
. 10.17.

, , :
, , .
, RecordFullClasses PLS-201:
rj PLS-201: identifier 'CLASSES' must be declared
PLS-201: identifier 'ALMOSTFULL' must be declared

, . , , , ,
, .
?
. PL/SQL
: , . GRANT REVOKE DDL. ,

385

. ,
, . . ,
SET
ROLE. , SET ROLE
, GRANT REVOKE
. ,
.
, , .
. ,
, .
, , ,
,


, . 10.15. UserA UserB temp_table, a RecordFullClasses UserA UserA. temp_table.
RecordFullClasses
(definer's rights),
,
.. .
OracleSi .
(invoker's rights)
, .
AUTHID. , (. 12).
, . AUTHID:
CREATE [OR REPLACE] FUNCTION _
[_] RETURN _
[AUTHID {CURRENTJUSER | DEFINER}] {IS | AS}
_;
CREATE [ORREPLACE] PROCEDURE _
[ _]
[AUTHID {CURRENT_USER | DEFINER}] {IS | AS}
_;
CREATE [OR REPLACE] PACKAGE __
[AUTHID {CURRENT_USER | DEFINER}] {IS | AS}
_;

386

10

AUTHID CURRENT_USER ( ), ,
DEFINER . (
AUTHID ) .
, RecordFullClasses
:
Q

invokers.sql
CREATE OR REPLACE PROCEDURE RecordFullClasses
AUTHID CURRENT_USER AS
- : classes AlmostFull
- UserA, UserA.
CURSOR c_Classes IS
SELECT department, course
FROM UserA.classes;
BEGIN
FOR v_ClassRecord IN c_Classes LOOP
- 1_1' ,
-- .
IF UserA.AlmostFull(v_ClassRecord.department,
v_ClassRecord.course) THEN
INSERT INTO temp_table (char_col) VALUES
(v_ClassRecord.department 1 1 ' ' 1 1 v_ClassRecord.course | |
' is almost full! ' ) ;
END IF;
END LOOP;
END RecordFullClasses;

invokers. sql UserA UserB,


, .
, ,
DBA.
invokers. sql invokers. out.,

RecordFullClasses UserB, UserB. temp_table, UserA UserA. temp_table. SQL*Plus


. 10.18.
- invokers.sql
SQL> connect UserA/UserA
Connected.

SQL> -- UserA;
SQL> -- UserA.temp_table.
SOL> BEG-IN
2
RecordFullClasses;
3
COMMIT;

4 END;
5 /
PL/SQL procedure successfully completed.

387

RecordFullClasses
( )

UserA

UserA
RecordFullClasses,
.

UserB
Users
RecordFullClasses,
.

. 10.18. RecordFullClasses
SQL> -- temp_table . .
SQL> SELECT * FROM temp_table;
MUM COL CHAR COL
MUS 410 is almost full!
SQL> -- UserB.
SQL> -- RecordFullClasses
SQL> -- UserB.temp_table.
SQL> BEGIN
2
UserA.RecordFullClasses;
3
COMMIT;
4 END;
5 /
PL/SQL procedure successfully completed.
SQL> -- .
SQL> SELECT * FROM temp_table;
NUM_COL
CHAR_COL
MUS 410 is almost full!

SQL- , .
PL/SQL (, ) - .
(GRANT) RecordFullClasses classes

388

10

(. . 10.18). AlmostFull PL/SQL,


UserA, UserB
.
, classes .
UserA ,
SQL- UserA.
U s e r B R e c o r d F u l l C l a s s e s
ORA-942 (. . 10.19):
invokers.sql
SQL> connect UserB/UserB
Connected.
SQL> BEGIN
2
UserA.RecordFullClasses;
3 END;
4 /
BEGIN
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-06512: at "USERA. RECORDFULLCLASSES", line 7
ORA-06512: at "USERA. RECORDFULLCLASSES", line 10
ORA-06512: at line 2

RecordFullClasses
( )

AlmostFull
1r

tempjtable

classes

UserA

UserA
RecordFullClasses,
.
. 10.19. SELECT classes

UserB

UserB
RecordFullClasses,
ORA-942,

389

ORA-942, PLS-201.
,
.

, classes
, . ,
(. . 10.17).
.
, . , , ,
(. . 10.20).
-- invokers.sql
SQL> connect UserA/UserA
Connected.
SQL> CREATE ROLE UserA_Role;
Role created.
SQL> GRANT SELECT ON classes TO UserA_Role;
Grant succeeded.
SQL> GRANT UserA_Role TO UserB;
Grant succeeded.
SQL> -- UserB .
SQL> connect UserB/UserB
Connected,
SQL> -- RecordFullClasses .
SQL> BEGIN
2
UserA.RecordFullClasses;

RecordFullClasses
( )

UserA

UserA Role

UserA
RecordFullClasses,
.
. 10.20.

UserB

UserB
RecordFullClasses,
.

390

10

COMMIT;

4 END;
5 /

PL/SOL procedure successfully completed.

,
, - .

,
. ,
SET ROLE (
SQL).
,
- ,
. PL/SQL,
.
.


SQL-
, SQL-.
, SQL-. PL/SQL 2.1 (Oracle? 7.1), OracleSz
.
, , ,
(, TO_CHAR, UPPER ADD_MONTHS).
Oracle
.
.


.
(purity level) , . 10.2.
:
, SQL-, (WNDS). ( OracleSz , , SELECT,
; . "
HsSQLBOracleSi".)

391


( ) ,
(RNPSnWNPS).
, SELECT, VALUES SET,
. WNPS.
, . , ,
, ( UPDATE),
WNDS , , SELECT.
PL/SQL
CHECK CREATE
TABLE ALTER TABLE, , ,
.
10.2.

WNDS


( DML).

( SELECT).

(

FETCH).

(


SQL-).

RNDS
WNPS

RNPS





He


, , , ,
SQL-. ,
.

.
.
IN, IN OUT
OUT.

392

10


, , PL/SQL, BOOLEAN RECORD.
NUMBER, CHAR, VARCHAR2, ROWID, LONG, RAW, LONG RAW
DATE, OracleS i 19.
, , .

COMMIT ROLLBACK, .
ALTER SESSION
ALTER SYSTEM.
FullName,
.

FullName.sql
CREATE OR REPLACE FUNCTION FullName (
p_StudentID students.ID%TYPE)
RETURN VARCHAR2 IS
v_Result VARCHAR2(1QO);
BEGIN
SELECT first_name || ' ' || last_name
INTO v_Result
FROM students
WHERE ID = p_StudentID;
RETURN v_Result;
END FullName;

FullName , SQL-:
(jj - FullName. sql
SQL> SELECT ID, FullName(ID) "Full Name"
2
FROM students;
ID Full Name

10000 Scott Smith


10001 Margaret Mason
10002 Joanne Junebug
10003 Manish Murgratroid
10004 Patrick Poll
10005 Timothy Taller
10006 Barbara Blues
10007 David Dinsmore
10008 Ester Elegant
10009 Rose Riznit

393

10010 Rita Razmataz


10011 Shay Shariatpanahy
12 rows selected.
SQL> INSERT INTO temp_table(char_col)
2 VALUES (FullName(10010));
1 row created.
RESTRICT REFERENCES
PL/SQL . SQL-,
. , . (
OracleSz) () RESTRICT_REFERENCES ( ). . :
PRAGMA RESTRICT_REFERENCES( 1___,
WNDS[, WNPS] [, RNDS] [, RNPS]);
___ ( OracleS DEFAULT
TRUST; . ). WNDS , SQL-, ( OracleSi
). . . , StudentOps RESTRICT_REFERENCES
:
FJ StudentOps.sql
CREATE OR REPLACE PACKAGE StudentOps AS
. FUNCTION FullName(p_StudentID IN students. ID%TYPE)

- flETURN VARCHAR2;
PRAGMA RESTRlCT_REFERENCES(FullName, WNDS, WNPS, RNPS);
/*. ,
. */
FUNCTION NumHistoryMajors
-V RETURN NUMBER;
PRAGMA RESTRICT_REFERENCES(NumHistoryMajors, WNDS);
END StudentOps;
. CREATE OR REPLACE PACKAGE BODY StudentOps AS
-- -.
:. vlNumHist NUMBER;
FUNCTION FullName(p_StudentIDIN students.ID%TYPE)
- RETURN VARCHAR2 IS
v_Result VARCHAR2(100);
BEGIN
SELECT first_name ' ' 1 1 last_name
INTO v_Result
FROM students

394

10

WHERE ID = p_StudentID;
RETURN v_Result;
END FullName;
FUNCTION NumHistoryMajors RETURN NUMBER IS
v_Result NUMBER;
BEGIN
IF v_NumHist IS NULL THEN
/* */
SELECT COUNT(*)
INTO v_Result
FROM students
WHERE major = 'History';
/* . */
v_NumHist :=v_Result;
ELSE
v_Result := v_NumHist;
END IF;
RETURN v_Result;
END NumHistoryMajors;
END StudentOps;

Oracle8\ .
PL/SOL

(. " SQL
Oracle8\").
RESTRICT_REFERENCES , ?
, . , PL/SQL,
, , .
,
. PL/SQL ,
,
.
( )
.
, .

395

PL/SQL
,
, OracleSL
,
,
.
SQL
RESTRICTJREFERENCES
OracleSi, .
. . ,

. RESTRICT _
REFERENCES, , .

CREATE OR REPLACE PACKAGE StudentOps AS


PRAGMA RESTRICT.REFERENCES (StudentOps, WNDS);
END StudentOps;

DEFAULT -
RESTRICT_REFERENCES,
. OracleS , .
DEFAULT:
PRAGMA RESTRICT_REFERENCES( DEFAULT,
WNDS[, WNPS] [, RNDS] [, RNPS]);
.
DefaultPragma:
Q

- DefaultPragma. sql
CREATE OR REPLACE PACKAGE DefaultPragma AS
FUNCTION F1 RETURN NUMBER;
PRAGMA RESTRICT_REFERENCES(F1, RNDS, RNPS);
PRAGMA RESTRICT_REFERENCES(DEFAULT, WNDS,

WNPS,

FUNCTION F2 RETURN NUMBER;


FUNCTION F3 RETURN NUMBER;
END DefaultPragma;
CREATE OR REPLACE PACKAGE BODY DefaultPragma AS
FUNCTION F1 RETURN NUMBER IS
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES (1, 'F1!');

RNDS,

RNPS);

396

10

RETURN 1;
END f1;
FUNCTION F2 RETURN NUMBER IS
BEGIN
RETURN 2;
END F2;
- .
FUNCTION F3 RETURN NUMBER IS
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES (1, ' F 3 ! ' ) ;
RETURN 3;
END F3;
END DefaultPragma;

( ) F2, F3. F3 temp_table, .



:
Q PL/SQL: Compilation unit analysis terminated.
PLS-00452: Subprogram ' F 3 ' violates its associated pragma
( . 'F3'
.)

RESTRICTJREFERENCES ,
. ,

. Test Fun :
Q -- Overload.sql
CREATE OR-REPLACE PACKAGE Overload AS
FUNCTION TestFunc(p_Parameter1 IN NUMBER)
RETURN VARCHAR2;
PRAGMA RESTRICT_REFERENCES(TestFunc, WNDS, RNDS, WNPS, RNPS);
FUNCTION TestFunc(p_ParameterA IN VARCHAR2,
p_ParameterB IN DATE)
RETURN VARCHAR2;
PRAGMA RESTRICT_REFERENCES(TestFunc, WNDS, RNDS, WNPS, RNPS);
END Overload;
CREATE OR REPLACE PACKAGE BODY Overload AS
FUNCTION TestFunc(p_Parameter1 IN NUMBER)
RETURN VARCHAR2 IS
BEGIN

397

RETURN 'Version 1';


END TestFunc;
FUNCTION TestFunc(p_ParameterA IN VARCHAR2,
p_ParameterB IN DATE)
RETURN VARCHAR2 IS
BEGIN
RETURN 'Version 2 ' ;
END TestFunc;
END Overload;

SQL*Plus , SQL
:
-- Overload.sql
SQL> SELECT Overload.TestFunc(1) FROM dual;
OVERLOAD.TESTFUNC(1)
Version 1
SQL> SELECT Overload.TestFunc('abc', SYSDATE) FROM dual;
OVERLOAD.TESTFUNCCABC', SYSDATE)
Version 2

RESTRICT_REFERENCES
, ,
.
PL/SQL , Oracle7.3 PL/SQL 2.3.
DBMS_OUTPUT, DBMS_PIPE, DBMS_ALERT,
DBMS_SQL UTL_FILE. (. 10.3). ,
OracleSi, , , , SQL-. ,
18, ,
.


("" ""),
, ,
10.3.
PL/SQL
( $ORACLE_HOME
rdbtns/admin).

398

10

10.3. RESTRICT_REFERENCES

DBMS_ALERT


- REGISTER COMMIT

DBMS_JOB

,
SQL

DBMS_OUTPUT

7.3.3

DBMS.PIPE

7.3.3

DBMS_SQL

EXECUTE PARSE
DDL, COMMIT

STANDARD

7.3.3 ( RAISE_APPLICATION_ERROR)

UTL.FILE

8.0.6

UTL HTTP

7.3.3



( ) .
SQL-
. , ; . FullName
:
SELECT FullName(p_StudentID => 10000) FROM dual;

SQL OracleS/
, RESTRICT_REFERENCES
. OracleSi SQL . OracleS . ,
.
(, , Java ). PL/SQL
, (.
12). , .
, SQL-. . ,
,
.
, StudentOps :
StudentOps2.sql
CREATE OR REPLACE PACKAGE StudentOps AS
FUNCTION FullName(p_StudentID IN students. ID%TYPE)

399

RETURN VARCHAR2;
/* ,
. */
FUNCTION NumHistoryMajors
RETURN NUMBER;
END StudentOps;
, , SQL:
SQL> SELECT StudentOps.FullNane(ID)
2
FROM students
3
WHERE major = 'History';
STUDENTOPS. FULLNAME(ID)
Margaret Mason
Patrick Poll
Timothy Taller
SQL> INSERT INTO temp_table(num_col)
2
VALUES (StudentOps.NumHistoryMajors);
1 row created.
SQL> SELECT * FROM temp_table;
NUM_COL CHAR_COL

SQL- , 18 "ORA-14551: Cannot perform a DML operation inside a query" ( DML ).


InsertTemp:
| InsertTemp.sql
CREATE OR REPLACE FUNCTION InsertTemp(
p_Num IN temp_table.num_col%TYPE,
p_Char IN temp_table.char_col%type)
RETURN NUMBER AS
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES (p_Num, p_Char);
RETURN 0;
END InsertTemp;

SELECT :
Q

-- InsertTemp.sql
SQL> SELECT InsertTempd, 'Hello')
2
FROM dual;
SELECT InsertTempd, 'Hello')
y

ERROR at line 1:
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "EXAMPLE. INSERTTEMP", line 6

400

10

ORA-06512: at line 1

TRUST
RESTRICT_REFERENCES ( ), ,
OracleS , . (. ). , , , , .
OracleS i TRUST,
.
TRUST , ,
, .
,
RESTRICT_REFERENCES, ,
. :
| - TrustPkg.sql
CREATE OR REPLACE. PACKAGE TrustPkg AS
FUNCTION ToUpper (p_a VARCHAfl2) RETURN VARCHAR2 IS
LANGUAGE JAVA
NAME 'Test.Uppercase(char[]) return chart"]';PRAGMA RESTRICT_REFERENCES(ToUpper, WNDS, TRUST);
PROCEDURE Derno(p_in IN VARCHAR2, p_out OUT VARCHAR2);
PRAGMA RESTRICT_REFERENCES(Demo, WNDS);
END TrustPkg;
CREATE OR REPLACE PACKAGE BODY TrustPkg AS
PROCEDURE Derno(p_in IN VARCHAR2, p_out OUT VARCHAR2) IS
BEGIN
p_out := ToUpper(p_in);
END Demo;
END TrustPkg;

TrustPkg.ToUpper ; Java,
. PL/SQL, TRUST. ToUpper
Demo, , WNDS.
\ '"

TrustPkg ,
Java, ,
Test. Uppercase.

i '

DML
OracleS , DML,
(.. WNDS).
OracleSi . ,

401

DML, , DML, . UpdateTemp:


PJ

-- DMLUpdate.sql
CREATE OR REPLACE FUNCTION UpdateTemp(p_ID IN students.ID%TYPE)
RETURN students. ID%TYPE AS
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES(p_ID, 'Updated!');
RETURN p_ID;
END UpdateTemp;

OracleSz
:
rj -- DMLUpdate.sql
SQL> UPDATE students
2 SET major = 'Nutrition'
3
WHERE UpdateTemp(ID) = ID;
WHERE UpdateTemp(ID) = ID
ERROR at :
ORA-06571: Function UPDATETEMP does not guarantee not to update database

OracleS? , UpdateTemp
students, temp_table.

, DML,
,
.


(shared pool) SGA,
- .
- . ,
. LRU (least recently used ).
"Oracle Concepts".
DBMS_SHARED_POOL (pin)
. ,
. , . ,
. ,
.

402

10

DBMS_SHARED_POOL : DBMS_SHARED_
POOL.KEEP, DBMS_SHARED_POOL.UNKEEP, DBMS_SHARED_POOL.SIZES
HDBMS_SHARED_POOL.ABORTED_REQUEST_THRESHOLD.

KEEP
DBMS_SHARED_POOL.KEEP
. , , , Java ( OracleS ), SQL-.
KEEP :
PROCEDURE KEEP(mmeVARCHAR2,
flag CHAR DEFAULT 'P');
.
,
DBMS_SHARED_POOL.UNKEEP. ,
DBMS_SHARED_POOL.KEEP , .

name

flag

VARCHAR2

CHAR

,
SQL-. SQL-
address hash_value v$sqlarea
(
SYS); SIZES.
. :
,
Q
R
(OracleS )
JS Java (OracleS )
JC Java (OracleS i )
JR Java (OracleS )
JD Java (OracleS )
SQL

UNKEEP
UNKEEP , .
. :
PROCEDURE UNKEEP(reawVARCHAR2,
flagCHAR DEFAULT ');

403

KEEP.
, .

SIZES

. SIZES :
PROCEDURE SIZES( minsize NUMBER);
, minsize.
SIZES DBMS_OUTPUT, SET
SERVEROUTPUT ON SQL*PIus Server Manager.

ABORTED_REQUEST_THRESHOLD
,
, ,
. .
ABORTED_REQUEST_THREASHOLD. :
PROCEDURE ABORTED_REQUEST_THRESHOLD( threshold_size NUMBER);
Oracle
, threashold_size .

PL/SQL, , .
, SQL-.
DBMS_SHARED_POOL. PL/SQL .

11

406

11

. PL/SQL .
, .
.


, PL/SQL ,
. ,
. , . ,
, . (firing). , , DML (INSERT, UPDATE DELETE),
. OracleSi
: , , DDL.
:
, ,
.
, ,
,
.
, ,
.
"- ".
: DML, .

Oracle8\ PL/SQL
,
(. " "
12).

407

DML
DML DML, . DML , (INSERT, UPDATE, DELETE).
,
.
, , ,
. major_stats:
rj - reliables.sql
CREATE TABLE major_stats (
major
VARCHAR2(30)
total_credits
NUMBER,
total_students NUMBER);

major_stats ,
students, major_stats
students. UpdateMajorStats.
DML students.
students major_stats :
Q

UpdateMajorStats. sql
CREATE OR REPLACE TRIGGER UpdateMajorStats
/* major_stats,
, students. */
AFTER INSERT OR DELETE OR UPDATE ON students
DECLARE
CURSOR c_Statistics IS
SELECT major, COUNT(*) total_students,
SUM(current_credits) total_credits
FROM students
GROUP BY major;
BEGIN
/* major_stats, .
. */
DELETE FROM major_stats;
/*
major_stats. */
FOR v_StatsRecord in c_Statistics LOOP
INSERT INTO major_stats (major, total_credits, total_students)
VALUES (v_StatsRecord.major, v_StatsRecord.total_credits,
v_StatsRecord.total_students);
END LOOP;
END UpdateMajorStats;

408

11

. , U p d a t e M a j o r S t a t s
INSERT, UPDATE DELETE.
DML, .

OracleS . (instead of) ( ,
). DML, DML,
DML, . .
classes_rooms:
;_j -- insteadOf .sql
CREATE OR REPLACE VIEW classes_rooms AS
SELECT department, course, building, room_number
FROM rooms, classes
WHERE rooms.room_id = classes.room_id;
,
, , SQL*Plus:
]

insteadOf .sql
SQL> INSERT INTO classes_rooms (department, course, building, room_number)
2
VALUES ('MUS', 100, 'Music Building', 200);
INSERT INTO classes_rooms (department, course, building, room_number)
*

ERROR at line 1:
ORA-01776: cannot modify more than one base table through a join view
:
Q - insteadOf.sql
CREATE TRIGGER ClassesRoomsInsert
INSTEAD OF INSERT ON classes_rooms
DECLARE
v_roomID rooms.room_id%TYPE;
BEGIN
- .
SELECT room_id
INTO v_roomID
FROM rooms

WHERE building = :new.building


AND room_number = :new.room_number;
- .
UPDATE CLASSES
SET room id = v roomlD

409

WHERE department = :new.department


AND course = :new.course;
END ClassesRoomsInsert;

ClassesRoomsInsert INSERT
, .

ClassesRoomsInsert
. , "
", .


18 .
DML, ,
, , . DDL,
. , . ,
:
:

-- LogCreations.sql
CREATE TABLE ddl_creations (
user_id
VARCHAR2(30),
object_type VARCHAR2(20),
object_name
VARCHAR2(30),
object_owner VARCHAR2(30),
creation date DATE);

. LogCreations ddl_creations

CREATE .

;;

-- LogCreations.sql
CREATE OR REPLACE TRIGGER LogCreations
AFTER CREATE ON SCHEMA
BEGIN

INSERT INTO ddl_creations (user_id, object_type, object_name,


object_owner, creation_date)
VALUES (USER, SYS.DICTIONARY_OBJ_TYPE, SYS.DICTIONARY_OBJ_NAME,
SYS.DICTIONARY_OBJ_OWNER, SYSDATE);
END LogCreations;


. :
CREATE [OR REPLACE] TRIGGER _

410

11

{BEFORE | AFTER | INSTEAD OF] _


_
[WHEN _]
[FOR EACH ROW]
_;
_ , _
, ( ), _
. _ .
_. WHEN (),
. , .

32 .
, ,

.

.

DML
DML INSERT (), UPDATE () DELETE (), . (BEFORE) (AFTER)
.
. 12 : 3 2 2 . DML:



11.1.
,
DML, : , INSERT
UPDATE. .
,
DML-. ,
AFTER DELETE.
. ( .)

411

11.1. DML

INSERT, DELETE
UPDATE
BEFORE AFTER

, DML .

.. ''

:
.
,
,
, .
,
.
FOR EACH ROW
( ) .

PL/SQL 2.1 (Oracle? 7.1)


12 .
COMPATIBLE
7.1 ,

.
DML
( ), . OracleSz

(. 8).

DML
DML.
DML :
1. BEFORE ( ).
2. , :
A. BEFORE ( ).
B. .
C. AFTER ( ).
3. AFTER ( ).
UPDATE classes. BEFORE AFTER:
- firingOrder.sql
CREATE SEQUENCE trig_seq
START WITH 1
INCREMENT BY 1;

412

11
CREATE OR REPLACE PACKAGE TrigPackage AS
-
v_Counter NUMBER;
END TrigPackage;
CREATE OR REPLACE TRIGGER classesBStatement
BEFORE UPDATE ON classes
BEGIN
- .
TrigPackage.v_Counter := 0;
INSERT INTO temp_table (num_col, char_col)
VALUES (trig_seq.NEXTVAL,
'Before Statement: counter = ' | I TrigPackage.v_Counter);
- .
TrigPackage.v_Counter := TrigPackage.v_Counter+ 1;
END ClassesBStatement;
CREATE OR REPLACE TRIGGER ClassesAStatementl
AFTER UPDATE ON classes
BEGIN
INSERT INTO temp_table (num_col. char_col)
VALUES (trig'_seq.NEXTVAL,
'After Statement 1: counter = ' | TrigPackage.v_Counter);
- .
TrigPackage.v_Counter := TrigPackage.v_Counter+ 1;
END ClassesAStatementl;
CREATE OR REPLACE TRIGGER ClassesAStatement2
AFTER UPDATE ON classes
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES (trig_seq.NEXTVAL,
'After Statement 2: counter = ' || TrigPackage.v_Counter);
- .
TrigPackage.v_Counter := TrigPackage.v_Counter+ 1;
END ClassesAStatement2;
CREATE OR REPLACE TRIGGER ClassesBRowl
BEFORE UPDATE ON classes
FOR EACH ROW
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES (trig_seq.NEXTVAL,
'Before Row 1: counter = ' || TrigPackage.v_Counter);
- .
TrigPackage.vJDounter := TrigPackage.v_Counter+ 1;
END ClassesBRowl;

413

CREATE OR REPLACE TRIGGER ClassesBRow2


BEFORE UPDATE ON classes
FOR EACH ROW
BEGIN
INSERT INTO temp_table (num_col, char__col)
VALUES (trig_seq.NEXTVAL,
'Before Row 2: counter = ' | TrigPackage.v_Counter);
- .
TrigPackage.v_Counter := TrigPackage.v_Counter+ 1;
END ClassesBRow2;
CREATE OR REPLACE TRIGGER ClassesBRowS
BEFORE UPDATE ON classes
FOR EACH ROW
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES (trig_seq.NEXTVAL,
'Before Row 3: counter = ' || TrigPackage.v_Counter);
- .
TrigPackage.v_Counter := TrigPackage,v_Counter+ 1;
END ClassesBRowS;
CREATE OR REPLACE TRIGGER ClassesARow
AFTER UPDATE ON classes
FOR EACH ROW
BEGIN
INSERT INTO temp_table (num_col, char_col)
VALUES (trig_seq.NEXTVAL,
'After Row: counter = ' || TrigPackage.v_Counter);
- .
TrigPackage.v_Counter := TrigPackage.v_Counter+ 1;
END ClassesARow;
UPDATE:
_| -- firingOrder.sql
UPDATE classes
SET num_credits = 4
WHERE department IN ( ' H I S ' , ' C S ' ) ;

. BEFORE AFTER ,
BEFORE AFTER . temp_table, :
) firingOrder.sql
SQL> SELECT * FROM temp_table
2
ORDER BY num_col;

414

11

NUM_COL CHAR_COL
1 Before Statement: counter = 0
Before Row 3 : counter 1
Before Row 2 : counter 2
Before Row 1 : counter 3

2
3
/1
5
6
7

After Row
Before Row
Before Row
8 Before Row
9
10
11
12
13
14
15
16
17
18
19

counter =
3 : counter
2 : counter
1 : counter

5
G
7

After Row : counter = 8


Before Row 3: counter = 9
Before Row 2: counter = 10
Before Row 1: counter = 11
After Row : counter = 12
Before Row 3: counter = 13
Before Row 2: counter = 14
Before Row 1: counter = 15
After Row : counter = 16
After Statement 2: counter = 17
After Statement 1: counter = 18

, , , .
( 10).
, , . , , . ,
.

_;c;_: Oracle
w
AFTER ROW,
DML

AFTER .

(
Oracle).
"Oracle Server Replication".


, .
, .
: old : new.
(correlation identifier) PL/SQL .
,

415

( ,
PL/SQL), PL/ SQL. PL/ SQL
_ , .
,
:nevf.nojie

, . : old : new 11.2.


, . .

: old INSERT,
DELETE : new.
. 'old INSERT : new
DELETE PL/SQL
, NULL.

OracleSz : parent.
, : old : new , : p a r e n t
(. Oracle).
11.2. :old :new
:old

INSERT
UPDATE
DELETE

:new

He
NULL

,

, ,

,

NULL

:1! :new GenerateNewStudentID, , : new. BEFORE,


INSERT, ID students ,
student_sequence.
Q - GenerateStudentlD.sql
CREATE OR REPLACE TRIGGER GenerateStudentID
BEFORE INSERT OR UPDATE ON students
FOR EACH ROW
BEGIN
/* ID students

416

11

student_sequence. ID - students,
:new.ID . */
SELECT student_sequence.NEXTVAL
INTO :new.ID
FROM dual;
END GenerateStudentID;

GenerateNewStudentID : new. ID. : new , , : new.


GenerateNewStudentID :
Q -- GenerateStudentID.sql
INSERT INTO students (first_name, last_name)
VALUES ('Lolita', 'Lazarus');

. ID, , ( ),
. ID, , .
[_| -- GenerateStudentID.sql
INSERT INTO students (ID, first_name, last_name)
VALUES (-7, 'Zelda', 'Zoom');

ID student_sequence. NEXTVAL, -7.


: new AFTER,
. , : new BEFORE; ; old , .
: new : old . - , .
( , ), : old : new . , ?
: new : old _%}', . ,
, : new : old. , - . . :
| -- pseudoRecords.sql
CREATE OR REPLACE TRIGGER TempDelete
BEFORE DELETE ON tempjiable
FOR EACH ROW
DECLARE

v_TempRec temp_table%ROWTYPE;
BEGIN
/* , :old . */

417

v_TempRec := :old;

/* , . */
v_TempRec.char_col := :old.char_col;
v_TempRec. num_col := :old.num_col;
END TempDelete;

, : old : new ,
_%7'.
REFERENCING REFERENCING : old : new. ,
WHEN:
REFERENCING [OLD AS _] [NEW AS _]
:old :new :_
:_. , REFERENCING . GenerateStudentID, REFERENCING
:new :new_student:
Q - GenerateStudentID.sql
CREATE OR REPLACE TRIGGER GenerateStudentID
BEFORE INSERT OR UPDATE ON students
REFERENCING new AS new _student
FOR EACH ROW
BEGIN
/* ID students
student_sequence. ID - students,
:new_student.ID . */
SELECT student_sequence.NEXTVAL
INTO :new_student.ID
FROM dual;
END GenerateStudentID;

WHEN
WHEN . WHEN
, , WHEN.
WHEN :
WHEN _

_ , . : new
: old, .
. , CheckCredits
, , , 20:
'Q CREATE OR REPLACE TRIGGER CheckCredits

418

11

BEFORE INSERT OR UPDATE OF current_credits ON students


FOR EACH ROW

WHEN (new.current_credits> 20)


BEGIN
/* */
END;

CheckCredits :
)

CREATE OR REPLACE TRIGGER CheckCredits


BEFORE INSERT OR UPDATE OF current_credits ON Students
FOR EACH ROW
BEGIN

IF :new.current_credits > 20 THEN


/* */
END IF;
END;

: INSERTING, UPDATING DELETING


UpdateMajorStats INSERT,
UPDATE DELETE. (
DML)
, .
() INSERTING, UPDATING DELETING.
.

L_

INSERTING

TRUE, INSERT;
FALSE .

UPDATING

TRUE, UPDATE;
FALSE .

DELETING

TRUE, DELETE;
FALSE .

/;

Oracleffi ,
(.
" / ").

LogRSChanges
, registered_students.
, . RS_audit,
:
_| tables.sql
CREATE TABLE RS_audit (
change_type
CHAR(1) NOT NULL,
changed_by
VARCHAR2(8) HOT NULL,

timestamp
DATE
old_student_id NUMBER(5),
old_department CHAR(3),
old_course
old_grade
new_student_id
new_department
new_course
new_grade

419

NOT NULL,

NUMBER(3),
CHAR(1),
NUMBER(5),
CHAR(3),
NUMBER(3),
CHAR(1)

);
LogRSChanges:
|

-- LogRSChanges. sql

CREATE OR REPLACE TRIGGER LogRSChanges


BEFORE INSERT OR DELETE OR UPDATE ON registered_students
FOR EACH ROW
DECLARE
v_ChangeType CHAR(1);
BEGIN
/* 'I' INSERT, ' 0 ' DELETE 'IT UPDATE. */
IF INSERTING THEN
v_ChangeType : = ' I';
ELSIF UPDATING THEN
v_ChangeType := ' U ' ;
ELSE
v_ChangeType := ' D ' ;
END IF;
/* RS_audit ,
registered_students.
SYSDATE,
- USER. */
INSERT INTO RS_audit
(changejiype, changed_by, timestamp,
old_student_id, old_department, old_course, old_grade,
new_student_id, new_department, new_course, new_grade)
VALUES
(v_ChangeType, USER, SYSDATE,
:old.student_id, :old.department, :old. course, :old.grade,
:new. student_id, :new.department, :new. course, :new.grade);
END LogRSChanges;

() ,
LogRSChanges. Oracle
, ,
. ,
LogRSChanges , , .
( RAISE_APPLICATION_ERROR)
, .

420

11


DML, INSERT, UPDATE DELETE ( , ), DML.
,
DML .
:
,
.
.
. 8.


(modifiable) , DML. , , :
(UNION, UNION ALL, MINUS)
(SUM, AVG ..)
GROUP BY, CONNECT BY START WITH
DISTINCT

, , ,
. , DML,
,
DML , 11.3 (.
"Oracle Concepts"). ,
, .
, .
11.3.
DML

INSERT

, , ,
.
,
.
,

UPDATE
DELETE

421^

11.3 , .
,
(. "Application Developer's Guide Fundamentals").


classes_rooms:
.- insteadOf.sql
CREATE OR REPLACE VIEW classes_rooms AS
SELECT department, course, building, room_number
FROM rooms, classes
WHERE rooms. room_id = classes.room_id;

. , , ,
. ,
classes_rooms DELETE
classes. DML classes_rooms? ,
. , :

INSERT
UPDATE

DELETE

.
classes .
, . classes, rooms,
, classes_rooms
.

. classes : ID
NULL.

ClassesRoomsInstead DML classes_rooms.


ClassesRoomsInsert,
:
-- ClassesRoomlnstead.sql
CREATE OR REPLACE TRIGGER ClassesRoomsInstead
INSTEAD OF INSERT OR UPDATE OR DELETE ON classes_rooras
FOR EACH ROW

DECLARE
v_roomID rooms.room_id%TYPE;
v_UpdatingClasses BOOLEAN := FALSE;
vJJpdatingRooms BOOLEAN := FALSE;
- ,
-- .

422

11

- , ORA-20000.
FUNCTION getRoomID(p_Building IN rooms.building%TYPE,
p_Room IN rooms. room_number%TYPE)
RETURN rooms.room_id%TYPE IS
v_RoomID rooms.room_id%TYPE;
BEGIN
SELECT room_id
INTO v_RoomID
FROM rooms
WHERE building = p_Building
AND room_number = p_Room;
RETURN v_RoomID;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20000, 'No matching room');
END getRoomID;
- , , ,
- p_Department p_Course. ,
- ORA-20001.
PROCEDURE verifyClass(p_Department IN classes.department%TYPE,
p_Course IN classes.course%TYPE) IS
vJDummy NUMBER;
BEGIN
SELECT 0
INTO v_Dummy
FROM classes
WHERE department = p_Department
AND course = p_Course;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE,APPLICATION_ERROR(-20001,
p_0epartment || ' ' || p_Course || ' doesn''t exist');
END verifyClass;
BEGIN
IF INSERTING THEN
- , .
- , (. );
- :
v_RoomID := getRoomID(:new.building, :new.room_number);
- classes .
UPDATE CLASSES
SET room_id = v_RoomID
WHERE department = :new.department
AND course = :new.course;
ELSIF UPDATING THEN
- , : classes rooms.


v_UpdatingClasses := (:new.department != :old.department) OR
(:new.course != :old.course);
v_UpdatingRooms := (:new,building != :old.building) OR
(:new.room_number != :old. room_number);
IF (vJJpdatingClasses) THEN
- .
- , .
verifyClass(:new.department, :new.course);
- .
v_RoomID := getRoomID(:old.building, :old. room_number);
- .
UPDATE classes
SET room_ID = NULL
WHERE department = :old.department
AND course = :old.course;
- , , .
UPDATE classes
SET room_ID = v_RoomID
WHERE department = :new.department
AND course = :new.course;
END IF;
IF vJJpdatingRooms THEN
- .
- . (. ), ,
- classes ;old, :new.
- .
v_RoomID := getRoomID(:new.building, :new.room_number);
- classes .
UPDATE CLASSES
SET room_id = v_RoomID
WHERE department = :old.department
AND course = :old.course;
END IF;
ELSE
- , ,
- .
UPDATE classes
SET room_ID = NULL
WHERE department = :old.department
AND course = :old.course;
END IF;
END ClassesRoomsInstead;

423

424

11


FOR EACH ROW
.
, .
ClassesRoomsInstead DML
.
. 11.1 classes, rooms classes_rooms.
INSERT:
[_| - ClassesRoomsInstead.sql
INSERT INTO classes_rooms
VALUES C M U S ' , 100, 'Music Building', 200);

Dept.

HIS
CS
ECN
CS
HIS
MUS
MUS
ECN
NUT

classes
Course
101
101
203
102
301
410
100
101
307

Room
ID
20000
20001
20002
20003
20004
20005

Room
ID
20000
20001
20002
20003
20004
20005

20007
20008

20006
20007
20008

rooms
Building
Building 7
Building 6
Building 6
Building 6
Building 6
Music
Building
Music
Building
Building 7
Building 7

classes rooms
Course
Building

Room
Number
201
101
150
160
170
100

Department
HIS
CS
ECN
CS
HIS
MUS

101
101
203
102
301
410

200

ECN
NUT

101
307

Building 7
Building 6
Building 6
Building 6
Building 6
Music
Building
Building 7
Building 7

Room
Number
201
101
150
160
170
100
300
310

300
310

. 11.1. classes, rooms classes_rooms


classes,
(. 11.2). UPDATE:

Dept.
HIS
CS
ECN
CS
HIS
MUS
MUS
ECN
NUT

classes
Course
101
101
203
102
301
410
100
101
307

Room
ID
20000
20001
20002
20003
20004
20005
20006
20007
20008

Room
ID
20000
20001
20002
20003
20004
20005
20006
20007
20008

rooms
Building
Building 7
Building 6
Building 6
Building 6
Building 6
Music
Building
Music
Building
Building 7
Building 7

classes rooms
Course
Building

Room
Number
201
101
150
160
170
100

Department
HIS
CS
ECN
CS
HIS
MUS

101
101
203
102
301
410

200

ECN
NUT
MUS

101
307
100

300
310

. 11.2.

Building 7
Building 6
Building 6
Building 6
Building 6
Music
Building
Building 7
Building 7
Music
Building

Room
Number
201
101
150
160
170
100
300
310
200

425

[_) ClassesRoomsInstead.sql
UPDATE classes_rooms
SET department = ' N U T ' , course = 307
WHERE building = 'Building 7' AND room_number = 201;

classes , . History 101 , a Nutrition 307 , History 101 (. . 11.3).


DELETE:
Q - ClassesRoomsInstead.sql
DELETE FROM classes_rooms
WHERE building = 'Building 6 ' ;

Dept.

classes
Course

HIS
CS
ECN
CS
HIS
MUS
MUS
ECN
HIS

101
101
203
102
301
410
100
101
307

Room
ID
20000
20001
20002
20003
20004
20005
20006
20007

Room
ID
20000
20001
20002
20003
20004
20005
20006
20007
20008

rooms
Building
Building 7
Building 6
Building 6
Building 6
Building 6
Music
Building
Music
Building
Building 7
Building 7

Room
Number
201
101
150
160
170
100

200

Department

classes rooms
Course
Building

HIS
CS
ECN
CS
MUS ,

301
101
203
102
410

ECN
NUT
MUS

101
307
100

300
310

Building 6
Building 6
Building 6
Building 6
Music
Building
Building 7
Building 7
Music
Building

Room
Number
170
101
150
160
100

300
210
200

. 11.3.
classes room_ID ,
Building 6, NULL
(. . 11.4). , DML
rooms ,
classes.
classes
Dept. Course Room
NUT
CS
ECN
CS
HIS
MUS
MUS
ECN
HIS

307
101
203
102
301
410
100
101
101

ID
20000

20005
20006
20007

rooms
Room
ID
20000
20001
20002
20003
20004
20005
20006
20007
20008

Building
Building 7
Building 6
Building 6
Building 6
Building 6
Music
Building
Music
Building
Building 7
Building 7

classes rooms
Room
Number
201
101
150
160
170
100

Department

Course

Building

MUS

410

ECN
NUT
MUS

101
307
100

Music
Building
Building 7
Building 7
Music
Building

200
300
310

. 11.4.

Room
Number
100

300
310
200

426

11


, DML DML ( ), INSERT,
UPDATE DELETE.
: DDL . DDL
CREATE, ALTER DROP, /
, / . :
CREATE [ORREPLACE] TRIGGER [.]_
{BEFORE | AFTER}
[cnucoK_co6umuu_ddl \ ___}
ON {DATABASE | [.]SCHEMA}
[_ WHEN]
_;
cnucoK_co6umuu_ddl DDL (
OR ()), ___
(
OR).
11.4 DDL (BEFORE AFTER).
. TRUNCATE
.
11.4. DDL

STARTUP

AFTER

SHUTDOWN

BEFORE

.
,
.

SERVERERROR

AFTER

LOGON

AFTER

LOGOFF

BEFORE

CREATE

BEFORE, AFTER

DROP

BEFORE, AFTER

ALTER

BEFORE, AFTER


ADMINISTER DATABASE TRIGGER
(. " ").

427



. , .
DATABASE SCHEMA. SCHEMA ,
, . , UserA
:
_| DatabaseSchema.sql
CREATE OR REPLACE TRIGGER LogUserAConnects
AFTER LOGON ON SCHEMA
BEGIN
INSERT INTO example.temp_table
VALUES (1, 'LogUserAConnects fired!');
END LogUserAConnects;

LogUserAConnects temp_table , UserA .


UserB:

] DatabaseSchema.sql
CREATE OR REPLACE TRIGGER LogUserBConnects
AFTER LOGON ON SCHEMA
BEGIN
INSERT INTO example.temp_table
VALUES (2, 'LogUserBConnects fired!');
END LogUserBConnects;

, example.
LogAllConnects , .
] DatabaseSchena. sql
CREATE OR REPLACE TRIGGER LogAllConnects
AFTER LOGON ON DATABASE
BEGIN
INSERT INTO example. temp_table
VALUES (3. 'LogAllConnects fired! ');
END LogAllConnects;


UserA UserB
(. DatabaseSchema. sql),

SQL*Plus ,
:
] DatabaseSchema.sql

428

11

SQL> connect UserA/UserA


Connected.
SQL> connect UserB/UserB
Connected.
SQL> connect example/example
Connected.
SQL>
SQL> SELECT * FROM temp_table;
NUM_COL CHAR_COL
3 LogAllConnects fired!
2 LogllserBConnects fired!
3 LogAllConnects fired!
3 LogAllConnects fired!
1 LogLlserAConnects fired!
, LogAllConnects (
), a LogUserAConnects LogUserBConnects .

STARTUP SHUTDOWN
.
, .

,
. (INSERTING,
UPDATING DELETING), . PL/SQL ( ),
.
11.5.
11.5.

SYSEVENT
INSTANCE_NUM

DATABASE_NAME



,
VARCHAR2(20)
.
NUMBER


.
Oracle Real
Application Clusters,
1.

VARCHAR2(50)
.

429

11.5. ()

SERVER ERROR

NUMBER

IS SERVERERROR

BOOLEAN

LOGIN USER

VARCHAR2(30)

DICTIONARY OBJ
TYPE

VARCHAR2(20)

DICTIONARY OBJ
NAME

VARCHAR2(30)

DICTIONARY OBJ
OWNER

VARCHAR2(30)

DES ENCRYPTED. VARCHAR2(30)


PASSWORD



SERVERERROR
.

,
.
1.

SERVERERROR
TRUE,
Oracle
.


,
.
CREATE, DROP, ALTER ,

DDL,
.
CREATE, DROP, ALTER ,

DDL,
.
CREATE, DROP, ALTER
,
DDL,
.
CREATE USER

ALTER USER
DES
.

SERVERERROR
SERVERERROR , .
SERVER_ERROR. , , , .
DBMS_UTILITY.
FORMAT_ERROR_STACK. ,
PL/SQL.
, :
) LogErrors.sql
CREATE TABLE error_log (

timestamp
username
instance
database_name
error_stack

DATE,
VARCHAR2(30),
NUMBER,
VARCHAR2(50),
VARCHAR2(2000)

430

11

, error_log:
)

-- LogErrors.sql
CREATE OR REPLACE TRIGGER LogErrors
AFTER SERVERERROR ON DATABASE
BEGIN
INSERT INTO error_log
VALUES (SYSDATE, SYS.LOGIN_USER, SYS.INSTANCE_NUM, S Y S .
DATABASE_NAME, DBMSJJTILITY.FORMAT_ERROR_STACK);
END LogErrors;

, LogErrors
. : SQL,
PL/SQL PL/SQL.
) LogErrors.sql
SQL> SELECT * FROM non_existent_table;
SELECT * FROM non_existent_table

ERROR at line 1:

ORA-00942: table or view does not exist


( )
SQL> BEGIN
2 INSERT INTO non_existent_table VALUES ('Hello!');
3 END;
4 /
INSERT INTO non_existent_table VALUES ('Hello!');
*

ERROR at line 2:
ORA-06550: line 2, column 15:
PLS-00201: identifier 'NON_EXISTENT_TABLE' must be declared
ORA-06550: line 2, column 3:
PL/SQL: SQL Statement ignored
( 'NON_EXISTENT_TABLE' .
SQL- .)
SQL> BEGIN
2
- !
3 DELETE FROM students
4 END;
5 /
END;
*

ERROR at line 4:
ORA-06550: line 4, column 1:
PLS-00103: Encountered the symbol "END" when expecting one of the
following:
. 9 ; return RETURNING. <an identified
<a double-quoted delimited-identifier> partition where
The symbol ";" was substituted for "END" to continue.

431

( "END", : . @ ; return
RETURNING. <> > partition where.
"END" ";".)
SQL> DECLARE
2
v_StringVar VARCHAR(2);
3 BEGIN
4
-- !
5 v_StringVar := 'abcdef ;
6 END;
7 /
DECLARE
*

ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character string
buffer too small
ORA-06512: at line 5
SQL> SELECT *
2
FROM error_log;
TIMESTAMP USERNAME INSTANCE DATABASE
ERROR_STACK
12-OCT-01 EXAMPLE
1 V901
ORA-00942: table or view does not exist
12-OCT-01 EXAMPLE
1 V901
ORA-06550: line 2, column 15:
PLS-00201: identifier 'NON_EXISTENT_TABLE' must be declared
ORA-06550: line 2, column 3:
PL/SQL: SQL Statement ignored
12-OCT-01 EXAMPLE
1 V901
ORA-06550: line 4, column 1:
PLS-00103: Encountered the symbol "END" when expecting one of the
following:
. @ ; return RETURNING_ <an identified
<a double-quoted delimited-identifier> partition where
The symbol ";" was substituted for "END" to continue.
12-OCT-01 EXAMPLE

1 V901

ORA-06502: PL/SQL: numeric or value error: character string


buffer too small
ORA-06512: at line 5



.
,
, .

432

11

STARTUP, SHUTDOWN, SERVERERROR LOGON


, LOGOFF DDL
.
, , , , COMMIT. DDL
( CREATE, ALTER DROP)
, .
LOGOFF
.
f


COMMIT,
.

WHEN
, DML, WHEN (). , :
STARTUP SHUTDOWN .
ERRNO SERVERERROR
.
LOGON LOGOFF
USERID USERNAME.
DDL
, .


, , ,
, .



. (namespace) , .
,
. , ,
, . ,
.
, ..
, - .

. , major_stats

433

major_stats, major_stats .
SQL*Plus:
-- samename.sql
SQL> -- ,
SQL> -- .
SQL> CREATE OR REPLACE TRIGGER major_stats
2
BEFORE INSERT ON major_stats

3 BEGIN
4
INSERT INTO temp_table (char_col)
VALUES ('Trigger fired! ');
6 END major_stats;
7

Trigger created.
SQL>
SQL>
SQL>
2
3
4
5

-- ,
-- .
CREATE OR REPLACE PROCEDURE major_stats AS
BEGIN
INSERT INTO temp_table (char_col)
VALUES ('Procedure called!');
END major stats;

6 /
CREATE OR REPLACE PROCEDURE major_stats AS
*

ERROR at line 1;
ORA-00955: name is already used by an existing object
( )


, .
, ,
.

(, TRGJ.
,
PL/SQL ( OracleSi
, . ). ,
PL/SQL,
:
: COMMIT, ROLLBACK, SAVEPOINT SET TRANSACTION. PL/SQL ,
, . , , ..
, .

11

434

, ,
,
( OracleSz , ,
, . 4).
, ,
( OracleS ).
LONG
LONG RAW. , : new : old
LONG LONG RAW , .
OracleS
LOB ( ),
. -.
. (constraints),
, (mutating)
(. ).


18 PL/SQL. OracleSz
GALL.
PL/ SQL Java. ,
Java. ,

:
'_] -- tables.sql
CREATE TABLE connect_audit (
user_name
VARCHAR2(30),
operation
VARCHAR2(30),
timestamp
DATE);

:
Q

..- LogPkgl.sql
CREATE OR REPLACE PACKAGE LogPkg AS
PROCEDURE LogConnect(p_UserID IN VARCHAR2);
PROCEDURE LogDisconnect(pJJserIDIN VARCHAR2);
END LogPkg;
CREATE OR REPLACE PACKAGE BODY LogPkg AS
PROCEDURE LogConnect(p_UserID IN VARCHAR2) IS
BEGIN
INSERT INTO connect_audit (user_name, operation, timestamp)
VALUES (p_USerID, 'CONNECT 1 , SYSDATE);

435

END LogConnect;
PROCEDURE LogDisconnect(p_UserIDIN VARCHAR2) IS
BEGIN
INSERT INTO connect_audit (user_name, operation, timestamp)
VALUES (p_USerID, 'DISCONNECT', SYSDATE);
END LogDisconnect;
END LogPkg;

LogPkg. LogConnect, LogPkg. LogDisconnect , connect_audit.


LOGON LOGOFF:
LogConnects.sql
CREATE OR REPLACE TRIGGER LogConnects
AFTER LOGON ON DATABASE
CALL LogPkg. LogConnect(SYS.LOGIN USER)
/

CREATE OR REPLACE TRIGGER LogDisconnects


BEFORE LOGOFF ON DATABASE
CALL LogPkg. LogDisconnect(SYS.LOGINJJSER)
,

LogConnects LogDisconnects
( ),
ADMINISTER
DATABASE TRIGGER.
LogConnects LogDisconnects CALL,
. .
PL/SQL,
Java. ,
Java:

_| Logger, java
import Java.sql.*;
import oracle.jdbc.driver.*;
public class Logger {
public static void LogConnect(String userlD)
throws SQLException {
// JDBC- .
Connection conn = new OracleDriver().defaultConnection();
String insertString =
"INSERT INTO connect_audit (user_name, operation, timestamp)" +
" VALUES (?, 'CONNECT', SYSDATE)";
// .

436

11

PreparedStatement insertStatement =
conn. prepareStatement(insertString);
insertStatement.setString(1, userlD);
insertStatement.execute();

I
public static void LogDisconnect(String userlD)
throws SQLException {
// JDBC- .
Connection conn = new OracleDriver().defaultConnection();
String insertString =
"INSERT INTO connect_audit (user_name, operation, timestamp)" +
" VALUES (?, 'DISCONNECT', SYSDATE)";
// .
PreparedStatement insertStatement =
conn.prepareStatement(insertString);
insertStatement.setString(1, userlD);
insertStatement.execute();

LogPkg:
rj LogPKg2. sql
CREATE OR REPLACE PACKAGE LogPkg AS
PROCEDURE LogConnect(p_UserID IN VARCHAR2);
PROCEDURE LogDisconnect(p_UserID IN VARCHAR2);
END LogPkg;
CREATE OR REPLACE PACKAGE BODY LogPkg AS
PROCEDURE LogConnect(p_UserID IN VARCHAR2) IS
LANGUAGE JAVA
NAME 'Logge r.LogConnect(j ava.lang.St ring)';
PROCEDURE LogDisconnect(p_UserIDIN VARCHAR2) IS
LANGUAGE JAVA
NAME ' Logger. LogDisconnect(java. lang. String)';
END LogPkg;
(. 12).

INSERTING, UPDATING DELETING,


:old : new ( : parent)
,
PL/SQL, CALL

437



(. 11.6). , , , . ,
, .
11.6. ,

CREATE TRIGGER
CREATE ANY TRIGGER

.

SYS.
.
,
SYS.
,
CREATE ANY TRIGGER,
.

SYS.

( ).
CREATE TRIGGER
CREATE ANY TRIGGER.

ALTER ANY TRIGGER

DROP ANY TRIGGER


ADMINISTER DATABASE
TRIGGER


,
. - ,
.



user_triggers.
, WHEN, . ,
UpdateMajorStats:
SQL> SELECT trigger_type, table_name, triggering_event
2
FROM user_triggers
3 WHERE trigger_name = 'UPDATEMAJORSTATS';
TRIGGER TYPE
TABLE NAME TRIGGERING EVENT
AFTER STATEMENT STUDENTS

INSERT OR UPDATE OR DELETE

438

11

user_triggers , . :
all_triggers , ( ),
dba_triggers .
.


, , .
:
DROP TRIGGER _;
_ .
.
OR REPLACE, .
, .
, ,
(DISABLE) . , .
ALTER TRIGGER:
ALTER TRIGGER _ {DISABLE | ENABLE};
(ENABLE)
. ALTER TRIGGER ,
. UpdateMajorStats:
SQL> ALTER TRIGGER UpdateMajorStats DISABLE;
Trigger altered.
SQL> ALTER TRIGGER UpdateMajorStats ENABLE;
Trigger altered.

, ALTER TABLE
,
ENABLE ALL TRIGGERS ( )
DISABLE ALL TRIGGERS ( ). :
SQL> ALTER TABLE students
2 ENABLE ALL TRIGGERS;
Table altered.
SOL> ALTER TABLE students
2
DISABLE ALL TRIGGERS;
Table altered.
status u s e r _ t r i g g e r s
'ENABLED', 'DISABLED', ,
. , DROP.

439

-
,
- . , .. .
,
,
. , .


.

. (mutating table) ,
DML. , . , DELETE CASCADE
( ) , (. "Oracle Server
Reference"). (constraining table) , .
registered_students:
) - tables, sql
CREATE TABLE registered_students (
student_id NUMBER(5)
NOT NULL,
department
CHAR(3)
NOT NULL,
course
NUMBER(3)
NOT NULL,
grade
CHAR(1),
CONSTRAINT rs_grade
CHECK (grade IN ( ' A ' , - B ' , T, ' D 1 , ' E ' ) ) ,
CONSTRAINT rs_student_id
FOREIGN KEY (student_id) REFERENCES students (id),
CONSTRAINT rs_department_course
FOREIGN KEY (department, course)
REFERENCES classes (department, course)

registered_students . students classes registered_students. , ,


/ DML.
registered_students DML.
SQL- :

440

11

, .
.

, ,

. .
. ,
(DELETE CASCADE).

INSERT ,
BEFORE AFTER,
,
. ,

. , INSERT
INTO table SELECT ...,
,
.

CascadeRSInserts. students classes, , students classes


. .
[ CascadeRSInsert.sql
CREATE OR REPLACE TRIGGER CascadeRSInserts
/* registered_students,
students classes INSERT
registered_students. */
BEFORE INSERT ON registered_students
FOR EACH ROW
DECLARE
v_Credits classes.num_credits%TYPE;
BEGIN
- .
SELECT num_credits
INTO v_Credits
FROM classes
WHERE department = :new.department
AND course = :new.course;
- .
UPDATE students
SET current_credits = current_credits + v_Credits

441

WHERE ID = :new.student_id;

- .
UPDATE classes
SET current_students = current_students + 1
WHERE department = :new.department
AND course = :new.course;
END CascadeRSInserts;


, , , . ,
students BEFORE INSERT
UPDATE:
rj LimitMajors.sql
CREATE OR REPLACE TRIGGER LimitMajors
/* ,
, 5. ,
raise_application_error . */
BEFORE INSERT OR UPDATE OF major ON students
FOR EACH ROW
DECLARE
v_MaxStudents CONSTANT NUMBER := 5;
v_CurrentStudents NUMBER;
BEGIN
- , .
SELECT COUNT()
INTO v_CurrentStudents
FROM students
WHERE major = :new.major;
- , .
IF v_CurrentStudents + 1 > v_MaxStudents THEN
RAISE_APPLICATION_ERROR(-20000,

'Too many students in major ' || :new.major);


END IF;
END LimitMajors;

,
. students , :
Q LimitMajors.sql
SQL> UPDATE students

2 SET major = 'History'


3 WHERE ID = 10003;
UPDATE students

ERROR at line 1:

442

11

ORA-04091: table EXAMPLE.STUDENTS is mutating, trigger/function

may not see it


ORA-06512: at "EXAMPLE.LIMITMAJORS", line 7
ORA-04088: error during execution of trigger ' EXAMPLE. LIMITMAJORS'
(ORA-04091: EXAMPLE,STUDENTS ,/,
, .
ORA-04088: 'EXAMPLE.LIMITMAJORS'.)

ORA-4091 , LimitMajors
, .
ORA-4091 , .

,

students .
, , .
LimitMaj rs ,
: new. major. ,
. : new. major, students . ,
, .
?
PL/SQL . , . ,
, , .
student_data RLimitMajors nSLimitmajors:
_)

mutating.sql
CREATE OR REPLACE PACKAGE StudentData AS
TYPE t_Majors IS TABLE OF students.majr%TYPE
INDEX BY BINARY_INTEGER;
TYPE t_IDs IS TABLE OF students. ID%TYPE
INDEX BY BINARY_INTEGER;
v_StudentMajors t_Majors;
v_StudentIDs
t_IDs;
v_NumEntries
BINARY_INTEGER := 0;
END StudentData;
CREATE OR REPLACE TRIGGER RLimitMajors
BEFORE INSERT OR UPDATE OF major ON students
FOR EACH ROW
BEGIN

/* StudentData. students

443

, ORA-4091. */
StudentData.v_NumEntries := StudentData.v_NumEntries+ 1;
StudentData.v_StudentMajors(StudentData.v_NumEntries) : =
:new.major;
StudentData.v_StudentIDs( StudentData. v_NumEntries):= :new.id;
END RLimitMajors;
CREATE OR REPLACE TRIGGER SLimitMajors
AFTER INSERT OR UPDATE OF major ON students
DECLARE
vJlaxStudentS
CONSTANT NUMBER := 5;
v_CurrentStudents NUMBER;
v_StudentID
students.ID%TYPE;
v_Major
students.major%TYPE;
BEGIN
/*
, . */
FOR v_Loop!ndex IN 1..StudentData.v_NumEntries LOOP
v_StudentID := StudentData.v_StudentIDs(v_Loop!ndex);
v_Major ;= StudentData.v_StudentMajors(v_Loop!ndex);
-- , .
SELECT COUNT(.)
INTO v_CurrentStudents
FROM students
WHERE major = v_Major;
- , .
IF v_CurrentStudents > vJlaxStudents THEN
RAISE_APPLICATION_ERROR(-20000,
'Too many students for major ' || v_Major ||
' because of student ' || v_StudentID);
END IF;
END LOOP;
- ,
-- .
StudentData.v_NumEntries := 0;
END LimitMajors;


LimitMajors.
. students , ,
:
Q mutating, sql
SQL> UPDATE students
2 SET major = 'History'
3
WHERE ID = 10003;

444

11

1 row updated.
SQL>
2
3
1 row

UPDATE students
SET major = 'History'
WHERE ID = 10002;
updated.

SQL> UPDATE students


2 SET major = 'History'

3 WHERE ID = 10009;
UPDATE students
*

ERROR at line 1:
ORA-20000: Too many students of major History because of student 10009
ORA-06512: at "EXAMPLE.SLIMITMAJORS", line 19
ORA-04088: error during execution of trigger 'EXAMPLE.SLIMITMAJORS'
( 1:
ORA-20000: - - 10009
ORA-06512: 19 "EXAMPLE.SLIMITMAJORS"
ORA-04088: 'EXAMPLE.SLIMITMAJORS')

, .
ORA-4091, .

AFTER. PL/SQL.

:
PL/SQL ,
, . ,
, , .
- StudentData. v_NumEntries.
0, .
, UPDATE,
, .
, , SLimitMajors. ,
AFTER, v_CurrentStudents
, ,
. v_CurrentStudents + 1,
LimitMajors, v_CurrentStudents.

445

PL/SQL
. , , UPDATE, ( OracleSz
). PL/SQL , .

PL/SQL Oracle. ,
. OracleS , DML, ,
.
PL/SQL.

12

448

12

3 11 PL/SQL.
.
"OracleS :
PL/SQL" (. "") Oracle.


PL/SQL, . , SQL, (bulk binds),
, ,
.


PL/SQL Oracle SQL. , .
. ,

. Java , .
, , .
OracleS PL/SQL
(, ) DBMSJPIPE
/ DBMS_ALERT. -, OCI (Oracle Call Interface Oracle) .
OracleS
. , , PL/SQL,
PL/SQL.
PL/SQL PL/SQL ( ), .
PL/SQL , . OracleS
( ). OracleS .
PL/SQL AS EXTERNAL.

449

OracleS i Java.
PL/SQL .
( )
PL/SQL. AS LANGUAGE.


(shared) , .
extproc. -,
. ,
.
, - sendMail
:
rj

int sendMail(
char subject,
char message,
char from,
char recipient);
, , /libs/libmail.so, :

Q CREATE OR REPLACE LIBRARY SendMailLibrary


AS '/libs/libmail.so';

:
1_J

CREATE OR REPLACE PROCEDURE SendMailC (


p_SubjeCt IN VARCHAR2,
p_Message IN VARCHAR2,
p_From IN VARCHAR2,
p_Recipient IN VARCHAR2)
AS EXTERNAL
LIBRARY SendMailLibrary
NAME "sendMail"
PARAMETERS (p_Subject STRING,
p_Message STRING,
p_From STRING,
pjtecipient STRING);

AS EXTERNAL
, PARAMETERS
PL/SQL .
SendMailC PL/SQL.
- sendMail, .

450

12

.
,
extproc ( Net8). extproc , LIBRARY, .

Java
Java Java (
Java Oracle).
, ,
PL/SQL . ,
.
, Java :
Qj public class sendMail
{
public static void send (
String subject,
String message,
String from,
String recipient)

PL/SQL , ,
.
PL/SQL:
CREATE OR REPLACE PROCEDURE SendMailJavaC
p_Subject IN VARCHAR2,

p_Message IN VARCHAR2,
p_From IN VARCHAR2,
p_Recipient IN VARQHAR2)
AS LANGUAGE JAVA

NAME ' sendMail.send(Java.lang.String, Java.lang.String,


java.lang.String, java.lang.String)';

NAME Java,
. ,
. ,
S e n d M a i l J a v a
PL/SQL, Java- sendMail. sendQ,
.
, Java
.
Java Java . extproc.

451

SQL
PL/SQL
SQL. , DML
PL/SQL.
SQL. SQL , PL/SQL.
SQL PL/SQL.
DBMS_SQL (. " "). OracleSz SQL.
SQL . , DBMS_SQL.

PL/SQL ,

,
(DML DDL) PL/SQL, EXECUTE IMMEDIATE.
SQL*Plus:
] execlmmediate.sql
SQL> DECLARE
2
v_SQLString VARCHAR2(200);
3
v_PLSQLBlock VARCHAR2(200);
4 BEGIN
*

5
6

7
8
9

10
11
12
13
14
15
16
17
18

19
20
21
22
23
24
25
26
27

- , . ,
- .

EXECUTE IMMEDIATE
'CREATE TABLE execute_table (call VARCHAR2(10))';
- , .
- .
FOR v_Counter IN 1..10 LOOP
v_SQLString :=
'INSERT INTO execute_table
VALUES ( " R o w ' 11 v_Counter 11 ' " ) ' ;
EXECUTE IMMEDIATE v_SQLString;
END LOOP;

- PL/SQL.
-
- ( ).
v_PLSQLBlock :=
'BEGIN
FOR v_Rec IN (SELECT * FROM execute_table) LOOP
DBMS_OUTPUT.PUT_LINE(v_Rec.call);
END LOOP;
END;';

452

12

28
29
30
31
32
33

- .
EXECUTE IMMEDIATE v_PLSQLBlock;
-- .
EXECUTE IMMEDIATE 'DROP TABLE execute_table-;

34 END;
35 /
Row 1
Row 2
Row 3
Row 4
Row 5
Row 6
Row 7
Row 8
Row 9
Row 10
PL/SQL procedure successfully completed.
EXECUTE
IMMEDIATE: DDL, DML PL/SQL.
, ( CREATE TABLE DROP TABLE) PL/SQL ( INSERT
). ,
DML DDL, .
EXECUTE IMMEDIATE
.
, .
PL/SQL,
USING EXECUTE IMMEDIATE, :
execBind.sql
DECLARE
v_SQLString VARCHAR2(1000);
v_PLSQLBlock VARCHAR2(1000);
CURSOR c_EconMajor IS
SELECT *
FROM students
WHERE major = 'Economies';
BEGIN
- ECN 103 classes,
- SQL.
v_SQLString :=
'INSERT INTO CLASSES (department, course, description,
max_students, current_students,
num_credits)
VALUS(:dep, :course, :descr, :max_s, :cur_s, :num_c)';

453

- INSERT, .
EXECUTE IMMEDIATE v_SQLString USING
'ECN', 103, 'Economics 103', 10, 0, 3;
- Economics .
FOR v_StudentRec IN c_EconMajor LOOP
- SQL, PL/SOL
- USING.
ECECUTE IMMEDIATE
'INSERT INTO registered_students
(student_ID, department, course, grade)
VALUES (:id, :dep, :course, NULL)'
USING v_Studentflec.ID, 'ENC', 103;
- , PL/SQL.
v_PLSQLBlock :=
'BEGIN
UPDATE classes SET current_students = current_students + 1
WHERE department = :d and course = :c;
END; ' ;
EXECUTE IMMEDIATE v_PLSQLBlock USING 'ECN', 103;
END LOOP;
END;


OPEN FOR . , , , PL/SQL, .
,
. USING,
EXECUTE IMMEDIATE. :
| -- NativeDynamic.sql
CREATE OR REPLACE PACKAGE NativeDynamic AS
TYPE t_RefCur IS REF CURSOR;
- students, WHERE,
- .
FUNCTION StudentsQuery(p_WhereClauseIN VARCHAR2)
RETURN t_RefCur;
- students
- .
FUNCTION StudentsQuery2(p_Major IN VARCHAR2)
RETURN t_RefCur;
END NativeDynamic;
CREATE OR REPLACE PACKAGE BODY NativeDynamic AS
- students WHERE
- .
FUNCTION StudentsQuery(p_WhereClause IN VARCHAR2)

454

12

RETURN t_RefCur IS
v_ReturnCursor t_RefCur;
v_SQLStatement VARCHAR2(500);
BEGIN
- WHERE.
v_SQLStatement := 'SELECT * FROM students ' || p_WhereClause;
- ,
OPEN v_ReturnCursor FOR v_SQLStatement;
RETURN v_ReturnCursor;
END StudentsQuery;
- students
- .
FUNCTION StudentsQuery2(p_Major IN VARCHAR2)
RETURN t_RefCur IS
v_ReturnCursor t_RefCur;
v_SQLStatement VARCHAR2(500);
BEGIN
v_SQLStatement := 'SELECT * FROM students WHERE major = :m';
- .
OPEN v_ReturnCursor FOR v_SQLStatement USING p_Major;
RETURN v_ReturnCursor;
END StudentsQuery2;
END NativeDynamic;
NativeDynamic :
| NativeDynamic. sql
SQL> DECLARE
2
vJStudent students%ROWTYPE;
3
v_StudentCur NativeDynamics.t_RefCur;
4 BEGIN
5
- StudentQuery,
6
-- ID
7
v_StudentCur :=
8
NativeDynamic.StudentsQueryCWHERE MOD(id, 2) = 0');

9
10
11
12
13
14
15
16
17
18
19

-
DBMS_OUTPUT.PUT_LINE('The following students have even IDs: ');
LOOP
FETCH v_StudentCur INTO v_Student;
EXIT WHEN v_StudentCur%NOTFOUND;
DBMS_OUTPUT.PUT_LINEC ' 1 1 v_Student.id | | ':
v_Student.first_name 1 1
v_Student.last_name);
END LOOP;
CLOSE v_StudentCur;

20
21

- StudentsQuery2,


22
23

455

v_StudentCur :=
NativeDynamic.StudentsQuery2(' Music');

24

25 -
26 DBMS_OUTPUT.PUT_LINE(
27
'The following students are music majors:');
28 LOOP
29
FETCH v_StudentCur INTO v_Student;
30
EXIT WHEN v_StudentCur%NOTFOUND;
31
DBMS_OUTPUT.PuT_LINE(' ' || v_Student.id || ': ' ||
32
v_Student.first_name 1 1 ' ' I I
33
v_Student.last_name);
34 END LOOP;
35 CLOSE v_StudentCur;
36 END;
37 /
The following students have even IDs:
10000: Scott Smith
10002: Joanne Junebug
10004: Patrick Poll
10006: Barbara Blues
10008: Ester Elegant
10010: Rita Razmataz
The following students are music majors:
10007: David Dinsmore
10009: Rose Riznit
PL/SQL procedure successfully completed.
EXECUTE IMMEDIATE EXECUTE IMMEDIATE , .
(. ) . ,
. :
| - NativeDynamic.sql
SQL> DECLARE
2
v_SQLQuery VARCHAR2(200);
3 v_Class classes%ROWTYPE;
4 v_Description classes.description%TYPE;
5 BEGIN
6
-
7 v_SQLOuery :=
8
'SELECT description ' 1 1
9
' FROM classes ' 1 1
10
' WHERE department = "ECN"' ||
11
'AND course = 203';
12
13 EXECUTE IMMEDIATE v_SQLQuery
14
INTO v_Description;

456

12

15
16

DBMS_OUTPUT.PUT.LINECFetched ' 1 1 v_Description);

17

18 - ,
19 v_SQLQuery :=
20
'SELECT * ' 1 1
21
' FROM classes ' 1 1
22
' WHERE description = idescription';
23
EXECUTE IMMEDIATE v_SQLQuery
24
INTO v_Class
25
USING v.Description;
26
27 DBMS_OUTPUT.PUT_LINE(
28
'Fetched ' || v_Class.department || ' ' || v_Class.course);
29
30
- , ORA-1422.
31 v_SQLQuery := 'SELECT * FROM classes';
32
EXECUTE IMMEDIATE v_SQLQuery
33
INTO v_Class;
34 END;
35 /
Fetched Economics 203
Fetched ECN 203
DECLARE
*

ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 32

ORA-1422 ,
.


SQL PL/SQL
SQL,
PL/SQL ( ). ,
,
PL/SQL, FOR
SQL.
PL/SQL SQL .
OracleSz
SQL ,
. ,
FORALL, :
]

~ FORALL.sql
DECLARE

TYPE t_Numbers IS TABLE OF temp_table.num_col%TYPE;

457

TYPE t_Strings IS TABLE OF temp_table.char_col%TYPE;


v_Numbers t_Numbers := t_Numbers(1);
v_Strings t_Strings := t_Strings(1);
- temp_table.
PROCEDURE PrintTotalRows (p_Message IN VARCHAR2) IS
v_Count NUMBER:
BEGIN
SELECT COUNT(*)
INTO v_Count
FROM temp_table;
DBMS_OUTPUT.PUT_LINE(p_Message || ': Count is ' || v_Count);
END PrintTotalRows;
BEGIN
- temp_table.
DELETE fROM temp_table;
-- PL/SQL, 1000 .
v_Numbers.EXTEND(1000);
v_Strings.EXTEND(1000);
FOR v_Count IN 1..1000 LOOP
v_Numbers(v_Count) := v_Count;
v_Strings(v_count) := 'Element' || v_Count;
END LOOP;
-- 1000 FORALL.
FORALL v_Count IN 1..1000
INSERT INTO temp_table VALUES
(v_Numbers(v_Count), v_Strings(v_Count));

- 1000 .
PrintTotalRowsCAfter first insert');
501 1000.
FORALL v_Count IN 501..1000
INSERT INTO temp_table VALUES
(v_Numbers(v_count), v_Strings(v_Count));
- 1500 .
PrintTotalRowsC'After second insert');
.
FORALL v_Count IN 1..1000
UPDATE tempjtable
SET char_col = 'Changed!'
WHERE num_col = v_Numbers(v_Count);
- , 1000 ,
- 1500 , WHERE
- 2 500 .
DBMS_OUTPUT.PUT_LINE(
'Update processed ' || SQL%ROWCOUNT || 'rows.');

458

12

, DELETE 300 .
FORALL V_Count IN 401..600
DELETE FROM tempjtable
WHERE nun_col = v_Numbers(v_Count);
- 1200 .
PrintTotalRowsCAfter delete');

END;

. :
[j| After first insert: Count is 1000
After second insert: Count is 1500
Update processed 1500 rows.
After delete: Count is 1200
, FORALL FOR.
INSERT, DELETE UPDATE. FORALL
,
.


DML
, . . OCI . :
) - .FORALL.sql
SQL> DECLARE
2
TYPE t_Strings IS TABLE OF temp_table.char_col%TYPE
3
INDEX BY BINARY_INTEGER;
4
TYPE t_Numbers IS TABLE OF temp_table. num_col%TYPE
5
INDEX BY BINARY_INTEGER;
6
v_Strings t_Strings;
7
v_Numbers t_Numbers;
8 BEGIN

10
11
12
13
14
15
16

17
18
19
20
21
22

- .

DELETE FROM temp_table;


FOR v_Count IN 1. .10 LOOP
v_Strings(v_Count) := '123456789012345678901234567890';
v_Numbers(v_Count) := v_Count;
END LOOP;
FORALL v_Count IN 1. .10

INSERT INTO tempjtable (num_col, char_col)


VALUES (v_Numbers(v_Count), v_Strings(v_Count));
-- v_Strings(6).
v_Strings(6) := v_Strings(6) | 'a';


23
24
25
26
27
28
29
30
31
32

459

- ,
- 5 .
FORALL v_Count IN 1..10
UPDATE temp_table
SET char_col = char_col 1 1 v_Strings(v_Count)
WHERE num_col = V_Nunbers(v_Count);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT. PUT_LINE('Got exception: ' ||SQLERRM);
COMMIT;

33 END:
34 /

Got exception: ORA-01401: inserted value too large for column


PL/SQL procedure successfully completed.
SQL> -- , 5
SQL> -- .
SQL> SELECT char_col

2
3

FROM temp_table
ORDER BY num_col;

CHAR_COL
1-23456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
10 row selected
Oracle9z FORALL
SAVE EXCEPTIONS. , , , .

SQL%BULK_EXCEPTIONS, PL/SQL.
SQL*Plus:
Q FORALL. sql
SQL> DECLARE
2
3
4
5
6
7
8

TYPE t_Strings IS TABLE OF temp_table. char_col%TYPE


INDEX BY BINARY_INTEGER;
TYPE t_Numbers IS TABLE OF temp.table. num_col%TYPE
INDEX BY BINARY_INTEGER;
v_Strings t_Strings;
v_Numbers t_Numbers;
v_NumErrors NUMBER;

460

9 BEGIN
10
- .
11 DELETE FROM temp_table;
12 FOR v_Count IN 1. .10 LOOP
13
v_Strings(v_Count) := '1234567890123456789012345678901;
14
v_Numbers(v_Count) := v_Count;
15 END LOOP;
16
17 FORALL v_Count IN 1.. 10
18
INSERT INTO temp_table (num_col, char_col)
19
VALUES (v_Numbers(v_Count), v_Strings(v_Count));
20
21
- t_Strings(6).
22 v_Strings(6) := v_Strings(6) || 'a';
23
24
- ,
25
- .
26 FORALL v_Count IN 1..10 SAVE EXCEPTIONS
27
UPDATE tempjtable
28
SET char_col = char_col 1 1 v_Strings(v_count)
29
WHERE num_col = v_Numbers(v_Count);
30 EXCEPTION
31 WHEN OTHERS THEN
32
DBMS_OUTPUT.PUT_LINECGot exception: ' || SQLERRM);
33
-- .
34
v_NumErrors := SQL%BULK_EXCEPTIONS.COUNT;
35
DBMS_OUTPUT.PUT_LINE(
36
' Number of errors during processing: ' || v_NumErrors);
37 FOR v_Count IN 1. .v_NumErrors LOOP
38
DBMS_OUTPUT.PUT_LINECError ' || v_Count || ' , iteration ' ||
39
SQL%BULK_EXCEPTIONS(v_Count).error_indexil 'is: ' ||
40
SQLERRM(0 - SQL%BULK_EXCEPTIONS(v_Count).error_code));
41 END LOOP;
42
43 COMMIT;
44 END;
45 /
Got exception: ORA-24381: error(s) in array DML
Number of errors during processing: 1
Error 1, iteration 6 is: ORA-01401: inserted value too large for column
PL/SQL procedure successfully completed.
SQL> -- , 1 - 5 7 - 10
SQL> -- , , 6 .
SQL> SELECT char_col
2 FROM temp_table
3 ORDER BY num_col;
CHAR_COL
123456789012345678901234567890123456789012345678901234567890

461

123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567890

10 row selected.

BULK COLLECT
FORALL DML.
BULK COLLECT.
SELECT INTO, FETCH INTO
RETURNING INTO. BULK COLLECT , :
] BULK_COLLECT. sql
DECLARE
TYPE tjlumbers IS TABLE OF temp_table.num_col%TYPE;
TYPE t_Strings IS TABLE OF temp_table. char_col%TYPE;
v_Numbers t_Numbers := t_Numbers(1);
v_String t_Strings := t_Strings(1);
v_Numbers2 t_Numbers;
v_Strings2 t_Strings;
CURSOR c_char IS
SELECT char_col
FROM tempjtable
WHERE num_col > 800
ORDER BY nuin_col;
BEGIN

- temp_table 1500 , 500

- .
v_Numbers.EXTEND(1500);
v_Strings.EXTEND(1500);
FOR v_Count IN 1..1000 LOOP
v_Numbers.(v_Count) := v_Count;
v_Strings(v_Count) := 'Elements' || v_Count;
IF v_Count > 500 THEN
v_Numbers(v_Count + 500) := v_Count;
v_Strings(v_Count + 500) := 'Element' || v_Count;
END IF;
END LOOP;
DELETE FROM temp_table;
FORALL v_Count IN 1..1500
INSERT INTO temp_table(num_col, char_col)

VALUES (v_Numbers(v_count), v_Strings(v_Count));

462

12
- .
SELECT num_col, char_col
BULK COLLECT INTO v_Numbers, v_Strings
FROM tempjtable
ORDER BY num_col;
DBMS_OUTPUT.PUT_LINE(
'First query fetched ' || v_Numbers.COUNT || ' rows');
- ,
- BULK COLLECT .
SELECT num_col
BULK COLLECT INTO v_Numbers2
FROM tempjtable;
DBMS_OUTPUT.PUT_LINE(
'Second query fetched ' || v_Numbers2. COUNT || ' rows');
- .
OPEN c_char;
FETCH c_char BULK COLLECT INTO v_Strings2;
CLOSE c_char;
DBMS_OUTPUT.PUT_LINE(
'Cursor fetch retrieved ' || v_Strings2.COUNT || ' rows');

END;

:
FJ First query fetched 1500 rows
Second query fetched 1500 rows
Cursor fetch retrieved 400 rows
PL/SQL procedure successfully completed.
BULK COLLECT
(SELECT INTO), (FETCH INTO).
, 1,
,
.
BULK COLLECT RETURNING INTO BULK COLLECT
RETURNING INTO
DML,
:
) - BULK_COLLECT. sql
SQL> DECLARE
2 TYPE t_Numbers IS TABLE OF temp_table. num_col%TYPE
3
INDEX BY BINARY_INTEGER;
4
TYPE t_Strings IS TABLE OF temp_table.char_col%TYPE
5
INDEX BY BINARY_INTEGER:
6 v_Numbers t_Numbers;
7
v_Strings t_Strings;

463

8 BEGIN
9 - , 55 .
10
- t_Numbers.
11 DELETE FROM tem_table;
12 FOR v_0uter IN 1. .10 LOOP
13
FOR v_Inner IN 1. .v_0uter LOOP
14
INSERT INTO temp_table (num_col, char_col)
15
VALUES (v_0uter, 'Element' | | v_Inner);
16
END LOOP;
17
v_Numbers(v_Outer) := v_0uter;
18 END LOOP;
19
20
- , .
21 FORALL v_Count IN 1..5
22
DELETE FROM temp_table
23
WHERE num_col = v_Numbers(v_Count)
24
RETURNING char_col BULK COLLECT INTO v_Strings;
25
26
- v_Strings 15 , 1+2+3+4+5.
27 DBMS_OUTPUT.PUT_LINE('After delete:');
28 FOR v_Count IN 1. . v_Strings.COUNT LOOP
29
DBMS_OUTPUT. PUT_LINE(
30
' v_Strings(' | v_Count [| ') = ' || v_Strings(v_Count));
31
END LOOP;
32 END;
33 /
After delete:
v_Strings(1) = Element #1
v_Strings(2) = Element #1
v_Strings(3) = Element #2
v_Strings(4) = Element #1
v_Strings(5) = Element #2
v_Strings(6) = Element #3
v_Strings(7) = Element #1
v_Strings(8) = Element #2
v_Strings(9) = Element #3
v_Strings(10) = Element #4
v_Strings(11) = Element #1
v_Strings(12) = Element #2
v_Strlngs(13) = Element #3
v_Strings(14) = Element #4
v_Strings(15) = Element #5
PL/SQL procedure successfully completed.


PL/SQL OracleS
. OracleS Oracle? . . , Point, :

464

12

] Point. sql
CREATE OR REPLACE TYPE Point AS OBJECT (
- .
NUMBER;
NUMBER;
- '(, )'.
MEMBER FUNCTION ToString RETURN VARCHAR2,
PRAGMA RESTRICT_REFERENCES(ToString, RNDS, WNDS, RNPS, WNPS),
- Point (SELF).
- , (, ).
MEMBER FUNCTION Distance(p IN Point DEFAULT Point(0, 0))
RETURN NUMBER
PRAGMA RESTRICT_REFERENCES( Distance, RNDS, WNDS, RNPS, WNPS),
- Point.
MEMBER FUNCTION Plus(p IN Point) RETURN Point;
PRAGMA RESTRICT_REFERENCES(Plus, RNDS, WNDS, RNPS, WNPS),
- Point * n
MEMBER FUNCTION Times(n IN NUMBER) RETURN Point,
PRAGMA RESTRICT_REFERENCES(Times, RNDS, WNDS, RNPS, WNPS)
CREATE OR REPLACE TYPE BODY Point AS
- '(, )'.
MEMBER FUNCTION ToString RETURN VARCHAR2 IS
v_Result VARCHAR2(20);
v_xString VARCHAR2(8) := SUBSTR(TO_CHAR(x), 1, 8);
v_yString VARCHAR2(8) := SUBSTR(TO_CHAR(y), 1, 8);
BEGIN
v_Result := '(' I I x_vString || ', ';
v_Result := v_Result || v_yString || ')';
RETURN v_Result;
END ToString;
- Point (SELF).
- , (, ).
MEMBER FUNCTION Distance(p IN Point DEFAULT Point (0,0))
RETURN NUMBER IS
BEGIN
RETURN SQRT(POWER(x - p.x, 2) + POWER(y - p.y, 2));
END Distance;
- Point.
MEMBER FUNCTION Plus(p IN Point) RETURN Point IS
v_Result Point;
BEGIN
v_Result := Point(x + p.x, + p.y);
RETURN v_Result;
END Plus;

465

- Point * .
MEMBER FUNCTION Times(n IN NUMBER) RETURN Point IS
v_Result Point;
BEGIN
v_Result := Point(x * n, * n);
RETURN v_Result;
END Times;
END;

Point . :
,
. , .
, , PL/SQL. , ToString, Distance, Plus
Times, PL/SQL, MEMBER.
PL/SQL,
.
, SQL*Plus:
rj Point, sql
SQL> DECLARE
2 v_Point1 Point := Point(1, 2);
3 v_Point2 Point;'
4 v_Point3 Point;
5 BEGIN
6 v_Point2 := v_Point1.Times(4);
7 v_Point3 := v_Point1.Plus(v_Point2);
8 DBMS_OUTPUT.PUT_LINECPoint 2: ' 1 1 v_Point2.ToString);
9 DBMSJXJTPUT. PUT_LINEf Point 3: ' | | v_Point3.ToString);
10 DBMSJHJTPUT.PUT_LINE('Distance between origins and point 1: ' ||
11
v_Point1.Distance);
12 DBMS.OUTPUT. PUT_LINEf Distance between point 1 and point 2: ' ||
13
v_Point1.Distance(v_Point2));
14 END;
15 /
Point 2: (4, 8)
Point 3: (5, 10)
Distance between origin and point 1:
2.23606797749978969640917366873127623544
Distance between point 1 point 2:
6.70820393249936908922752100619382870632
PL/SQL procedure successfully completed.

466

12

, ,
. .


SQL. , ,
. , SQL :
j_j - PointSQL.sql
SQL> CREATE TABLE point_object_tab OF Point;
Table created.
SQL> CREATE TABLE point_column_tab (

2
key VARCHAR2(20),
3
value Point);
Table created.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
28
29
30
31

DECLARE
v_Point Point ;= Point(1, 1);
v_NewPoint Point;
v_Key point_column_tab.ket%TYPE;
v_XCoord NUMBER;
v_YCoord NUMBER;
BEGIN
- .
INSERT INTO point_object_tab VALUES (v_Poi,nt);
INSERT INTO point_column_tab VALUES ('My Point', v_Point);
-
- , .
SELECT *
INTO v_XCoord, v_YCoord
FROM point_object_tab;
DBMS_OUTPUT.PUT_LINE('Relational query of object table: ' ||
v_XCoord || ', ' || v_YCoord);
- VALUE,
- .
SELECT VALUE(ot)
INTO v_NewPoint
FROM point_object_tab ot;
DBMS_OUTPUT.PUT_LINECobject table; ' | | v_NewPoint.ToString);
-
- .
SELECT key, velue
INTO v_Key, vJJewPoint
FROM point_column_tab;


32

467

DBMS_OUTPUT.PUT_LINECcolumn_table: ' 1 1 v_NewPoint.ToString);

33
34 END;
35 /

Relational query of object table: 1, 1


object table: (1, 1)
PL/SQL procedure successfully completed.
, ( ),
VALUE.

, , (persistent). .
, .
REF REF INTO INSERT.
:
- PointSQL.sql
SQL> DECLARE
2 v_PointRef REF Point;
3
v_Point Point;
4 BEGIN
5
DELETE FROM point_object_tab;
6
7
- .
8
INSERT INTO point_object_tab (x, )
9
VALUES (, );
10
INSERT INTO point_object_tab (x, )
11
VALUES (1, 1);
12'
13
- .
14
SELECT REF (ot)
15
INTO v_PointRef
16
FROM point_object_tab ot
17
WHERE x = 1 AND = 1;
18
19
- , .
20
SELECT DEREF (v_PointRef)
21
INTO v_Point;
22
FROM dual;
23 DBMS_OUTPUT.PUT_LINE('Selected reference ' ||
24
v_Point.ToString);
25
26
-
27
- REF INTO.
28
INSERT INTO point_object_tab ot (x, y)
29
VALUES(10, 10)
30
RETURNING REF (ot) INTO v_PointRef;

468

12

31 END;
32 /

Selected reference (1, 1)


PL/SQL procedure successfully completed.


(LOB, large object) , ,
. Oracle
? Oracle? VARCHAR2
2000 . , VARCHAR2
, . LONG 2
, a LONG RAW . LONG
LONG RAW Oracle?
LOB. LONG LONG
RAW , , LONG LONG RAW.
, LONG
LONG RAW Oracle Call,
LONG DBMS_SQL. LONG LONG DATA ,
.
Oracle? LOB.
OracleS LONG LONG RAW (
), VARCHAR2 4000 . . , OracleS
LOB. LOB, : CLOB, NCLOB, BLOB
BFILE (. 12.1).
12.1. LOB
LOB
CLOB
LONG Oracle?, CLOB ,
.
NCLOB NCLOB
. Oracle8/ NCLOB
.
BLOB
LONG RAW Oracle?, BLOB
, .
BFILE
BFILE ,
Oracle. LOB,
BFILE , Oracle.
. BFILE
Oracle.

469

, CLOB, NCLOB BLOB LOB. BFILE


LOB. LOB :
LOB 4 (LONG LONG RAW
Oracle? OracleS 2 ).
LOB , OCI OracleS DBMSJLOB PL/SQL. LOB
LOB
( BFILE, ).
LONG LONG RAW
LOB. ,
LOB ( )
.
LOB, LOB
.
NCLOB, NCLOB.
LOB .
LOB SQL
DML LOB. ,
, LOB.
LOB
LONG LONG RAW, LOB . LOB , LOB.
LOB. DBMS_LOB, Oracle Call, */++
Pro*COBOL, Oracle Objects OLE JDBC. LOB
SQL, ( DBMS_LOB " "):
) - LOB_DML.sql
SQL> CREATE TABLE lobdemo (
2
key NUMBER PRIMARY KEY,
3 clob_lob CLOB,
4
blob_col BLOB,
5 bfile_col BFILE,

6 );

Table created.
SQL> -- INSERT .
SQL> INSERT INTO lobdemo (key, clob_lob, blob.col, bfile_col)
2 VALUES (50, 'This is a character literal',
3
HEXTORAW('FEFEFEFEFEFEFEFEFE'),
4
NULL);
1 row created.

470

12

SOL> INSERT INTO lobdemo (key, clob_col, blob_col, bfile_col)


2 VALUES (51, 'This is another character literal',
3 HEXTORAW('ABABABABABABABABABABA'),
4 NULL);

1 row created.

SQL> -- INSERT .
SQL> -- 50 51 60 61.
SOL> INSERT INTO lobdemo
2
SELECT key + 10, clob_col, blob_col, NULL
3
FROM lobdemo
4
WHERE key IN (50, 51);
2 rows created.
SQL> -- blob_col .
SQL> UPDATE lobdemo
2
SET blob_col = HEXTORAWCCDCDCDCDCOCDCDCDCDCD')
3
WHERE key IN (60, 61);
2 rows updated.
SQL> -- , 61.
SQL> DELETE FROM lobdemo
2 WHERE key = 61;
1 row deleted.
, LOB ,
VARCHAR2 RAW,
4000 (
VARCHAR2).
.


PL/SQL REF CURSOR, . REF
CURSOR , .
,
. OracleQ . (
)
SQL, .
, , . ,
, . ,
20 :
) pipelined.sql
CREATE TYPE MyType AS OBJECT (
fieldl NUMBER,

471

field2 VARCHAR2(50));
CREATE TYPE MyTypeList AS TABLE OF MyType;
CREATE OR REPLACE FUNCTION PipelineMe(
RETURN MyTypeList PIPELINED AS
v_MyType MyType;
BEGIN
FOR v_Count IN 1..20 LOOP
v_MyType := MyType(v_Count, 'Row ' | v_Count);
PIPE ROW(v_MyType);
END LOOP;
RETURN;
END PipeLineMe;


. PIPE ROW . RETURN.
SQL TABLE:
Q - pipelined.sql
SQL> SELECT *
2
FROM TABLE (PipelineMe);
FIELD1 FIEL02

Row 1
2 Row 2
3 Row 3

4
5
6
7
8
9
10
11

Row 4
Row 5
Row 6
Row 7
Row 8
Row 9
Row 10

Row 11
12 Row 12

13 Row
Row
Row
Row
17 Row
18 Row
19 Row
20 Row
14
15
16

13
14
15
16
17
18
19
20

20 rows selected.

, . .

472

12


PL/SQL , , . ,
.
.

DBMS_SQL
DBMS_SQL SQL PL/SQL.
,
SQL ( 18 ).
DBMS_SQL
, , . DBMS_SQL.
Q - dynamicDML sql
CREATE OR REPLACE PROCEDURE UpdateClasses(
/* DBMS_SQL ,
- .

*/
p_Department IN classes.department%TYPE,
p_NewCredits IN classes. num_credits%TYPE,
p_RowsUpdated OUT INTEGER) AS
v_CursorID INTEGER;
vJJpdateStmt VARCHAR2(100);
BEGIN
- .
v_CursorID := DBMS_SQL.OPEN_CURSOR;
- SQL.
v_UpdateStmt :=
'UPDATE classes
SET num_credits = :nc
WHERE department = :dept';
- .
DBHS_SQL.PARSE(v_CursorID, vJjpdateStrat, DBMS_SQL.NATIVE);
- p_NewCredits :.
- BIND_VARIABLE p_NewCredits NUMBER,
- .
DBMS_SQL.BIND._VARIABLE(v_CursorID, ':nc', p_NewCredits);
- p_Department :dept.
- BIND_VARIABLE p_Department CHAR, .
DBMS_SQL.BIND_VARIABLE_CHAR(v_CursorID, ':depf, p_Department);
-

473

p_RowsUpdated := DBMS_SQL.EXECUTE(v_CursorID);
-
DBMS_SQL.CLOSE_CURSOR(v_CursorID);
EXCEPTION

WHEN OTHERS THEN


.
DBMS_SQL.CLOSE_CURSOR(v_CursorID);

RAISE;
END UpdateClasses;

DBMS_PIPE
DBMS_PIPE , .
, .
PL/SQL , . , DBMS_PIPE
*.
, .
(pipe)
. , , , , ROLLBACK. ,
.
, , .
. , SQL*Plus :
rj PipeSend.sql
DECLARE
v_PipeName VARCHAR2(30) := 'MyPipe';
v_Status INTEGER;
BEGIN
- . ,
varchar2.
DBMS_PIPE.PACK_MESSAGE(SYSDATE);
DBMS_PIPE.PACK_MESSAGE(123456);

DBMS_PIPE.PACK_MESSAGE('This is a message sent from the pipe!');


-- .
v_Status := DBMS_PIPE.SEND_MESSAGE(v_PipeName);
IF v_Status ! = 0 THEN
DBMS_OUTPUT.PUT_LINECError ' || v_Status ||
'while sending message');
END IF;
END;

474

12

, , , MyPipe. ( )
SQL*Plus, , :
Q "~ PipeReceive.sql
DECLARE

v_PipeName VARCHAR2(30) := 'MyPipe';


v_Status INTEGER;
v_DateVal DATE;
v_NumberVal NUMBER;
v_StringVal VARCHAR2(100);
BEGIN
- . ,
-- .
v_Status := DBMS_PIPE.RECEIVE_MESSAGE(v_PipeName);
If (v_Status != 0 THEN
DBMS_OUTPUT.PUT_LINECError ' || v_Status ||
'while receiving message');
END IF;
- .
- , .
DBMS_PIPE.UNPACK_MESSAGE(v_DateVal);
DBMS_PIPE.UNPACK_MESSA6E(v_NumberVal);
DBMS_PIPE.UNPACK_MESSAGE(v_StringVal);
- .
DBMS_OUTPUT.PUT_LINECUnpacked ' | v_DateVal);
DBMS_OUTPUT.PUT_LINE('Unpacked ' || v_NumberVal);
DBMS_OUTPUT.PUT_LINE('Unpacked ' || v_StringVal);

END;

DBMS_PIPE ,
VARCHAR2, NUMBER, DATE, RAW ROWID.
DBMS_PIPE.
Oracle Advanced Queuing.

DBMS_ALERT
DBMS_PIPE, DBMS_ALERT
, . :
(alert) . ,
COMMIT. ,
.
. ,
. , , .

475

,
. .
, .
,
.

DBMS_ALERT.SIGNAL:
- AlertSend.sql
DECLARE
v_AlertName VARCHAR2(30) := 'MyAlerf;
BEGIN
- SIGNAL.
DBMS_ALERT.SIGNAL(v_AlertName, 'Alert! Alert! Alert!');
- , COMMIT.
COMMIT;
END;

WAITONE WAITANY. WAITONE:


Q -- AlertReceive.sql
DECLARE
v_AlertName VARCHAR2(30) := 'MyAlerf;
v_Message VARCHAR2(100);
v_Status INTEGER;
BEGIN
- , .
DBMS_ALERT.RE6ISTER(v_AlertName);
- .
DBMS_ALERT.WAITONE(v_AlertName, v_Message, v_Status);
IF v_Status = 0 THEN
DBMS_OUTPUT.PUT_LINE('Received: ' 1 1 v_Message);
ELSE
DBMS_OUTPUT.PUT_LINECWAITONE timed out');

END IF;
END;

UTL_FILE
PL/SQL
; SQL.
UTL_FILE PL/SQL
.
, ,
(, NFS).

476

12

UTL_FILE , .
.
:
, Oracle.
UTL_FILE_DIR init.ora.
UTL_FILE_DIR
(*), , .
. :
- UTL_FILE.sql
DECLARE

v_FileHandle UTL_FILE.FILE_TYPE;
BEGIN
- /tmp7utl_file.txt .
- , .
- , .
v_FileHandle := UTL.FILE.FOPENC/tmp/1, 'utl_file.txt', 'w');
- .
UTL_FILE.PUT._LINE(v_FileHandle, 'This is line 1);
FOR v_Counter IN 2..11 LOOP
UTL_FILE.PUTF(v_FileHandle, 'This is line Xs!\n', v_Counter);
END LOOP;
- .
UTL_FILE. FCLOSE(v_FileHandle);

END;

/tmp7utl_file.txt
:
This
This
This
This
This
This
This
This
This
This
This

is line 1!
is line 2!
is line 3!
is line 4!
is line 5!
is line 6!
is line 7!
is line 8!
is line 9!
is line 10!
is line 11!

UTL_FILE
. , UTL_FILE .

477

UTLJTCP
UTL_FILE, UTLJTCP PL/SQL
. UTLJTCP
, TCP. UTL_TCP
HTTP :
PJ - UTL_TCP,sql
DECLARE
v_Connection UTLJCP.CONNECTION;
v_NumWritten PLS_INTEGER;
BEGIN
- 80, HTTP.
v_Connection := UTL_TCP.OPEN_CONNECTION('www.oracle.com', 80);
- HTTP,
v_NumWritten := UTL_TCP.WRITE_LINE(v_Connection, 'GET /HTTP/1.01);
v_NumWritten := UTL_TCP.WRITE_LINE(v_Connection);
- 10 .
BEGIN
FOR v__Count IN 1. . 10 LOOP
DBMS_OUTPUT.PUT_LINE(UTL_TCP.GET_LINE(v_Connection, TRUE));
END LOOP;
EXCEPTION
WHEN UTL_TCP.END_OF_INPUTTHEN
NULL;
END;
UTL_TCP.CLOSE_CONNECTION(v_Connection);

END;

UTL_TCP , TCP. UTLJ5MTP, UTLJHTTP


UTL_INADDR , UTL_TCP .

UTL_SMTP
UTL_SMTP UTL_TCP SMTP, e-mail.
SMTP . :
]

-- UTL_SMTP.sql
DECLARE
v_FromAddr VARCHAR2(50) := 'Oracle';
v_ToAddr VARCHAR2(50) := 'YOUR_EMAIL_ADDRESS';
v_Message VARCHAR2(200);
- SMTP. Unix 'localhost'.
vJlailHost VARCHAR2(50) := 'localhosf ;
v MailConnection UTL_SMTP.Connection;

478

12

BEGIN
- . (from, subject ..)
- ,
-- CHR(10).
v_Message :=
'From: ' || v_FromAddr || CHR(10) ||
'Subject: Hello from PL/SQL1 || CHR(10) ||
'This message sent to you courtesy of the UTL_SMTP package.';
- .
v_MailConnection := UTL_SMTP.OPEN_CONNECTION(v..MailHost);
- SMTP, e-mail.
UTL_SMTP.HELO(v_MailConnection, v_MailHost);
UTL_SMTP.MAIL(v_MailConnection, v_FromAddr);
UTL_SMTP.RCPT(v_MailConnection, v_ToAddr);
UTL_SMTP.DATA(v_MailConnection, v_Message);
- .
UTL_SMTP.QUIT(v_MailConnection);
END;
UTL_SMTP e-mail
SMTP; SMTP.

UTL_HTTP
UTLJHTTP HTTP PL/SQL
HTTP ( Web). UTL_HTTP OracleS (
). HTTP
( UTLJHTTP.REQUEST)
( UTLJHTTP.REQUEST J?IECES).
:
] - UTL_HTTP.sql
CREATE TABLE http_results (
sequence_no NUMBER PRIMARY KEY,
piece VARCHAR2(2000));
DECLARE

v_Result UTL_HTTP.HTML_PIECES;
vJJRL VARCHAR2(100) := 'http://www.oracle.com';
v_Proxy VARCHAR2(100) := 'YOUR_PROXY_SERVER';
BEGIN
- UTL_HTTP
- 8.0.6. 10 ,
- 2000 .
v_Result := UTL_HTTP.REQUEST_PIECES(v_URL, 10, v_Proxy);
FOR v_Count IN 1..10 LOOP
INSERT INTO http_results VALUES (v_Count, v_Result(v_Count));
END LOOP;

479

END;

OracleSz UTL_HTTP HTTPS. 19 UTL_HTTP, HTTPS, cookies, ,


Web.

UTLJNADDR
UTL_INADDR GET_HOST_ADDRESS,
IP- . GET_HOST_NAME
.
Oracle9 GET_HOST_NAME IP- .
UTLJNADDR:
- UTL_INADDR.sql
DECLARE

v_HostName VARCHAR2(100) := 'www.oracle.com';


BEGIN
DBMS_OUTPUT.PUT_LINE(' Address of ' | v_HostName || ' is ' ||
UTL_INADDR.GET_HOST_ADDRESS(v_HostName));
DBMS_OUTPUT.PUT_LINE('Name of local host is ' 1 1
UTL_INADDR. GET_HOST_NAME);

END;

DBMS_JOB
DBMS_JOB PL/SQL , UNDC- .
Oracle. , in it. :
JOB_QUEUE_PROCESSES
. 0 ,
.
JOB_QUEUE_INTERVAL , ,
.
JOB_QUEUE_INTERVAL .
, Templnsert:

- DBMS_JOB.sql
CREATE SEQUENCE temp_seq
START WITH 1
INCREMENT BY 1;
CREATE OR REPLACE PROCEDURE Templnsert AS
BEGIN

480

12

INSERT INTO temp_table (num_col, char_col)


VALUES (temp_seq.NEXTVAL,
TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24: MI:SS'));
COMMIT;
END Templnsert;

Templnsert 90 SQL*Plus:
Q

DBMS_JOB.sql
SQL> VARIABLE v_JobNum NUMBER
SQL> BEGIN
2
DBMS_JOB,SUBMIT(:v_JobNura, 'Teraplnsert;', SYSDATE,
3
'SYSDATE+ (90/(24*60*60))');

COMMIT;

5 END;
6

PL/SQL procedure successfully completed.


SQL>
SQL> PRINT v_JobNum
V JOBNUM

SUBMIT .
90 'SYSDATE + (90/(24*60*60))', .
, COMMIT , , Templnsert. , ,
, .
,
. ,
DBMSJOB.REMOVE:
DBMS_JOB.sql
BEGIN
DBMS_JOB.REMOVE(:v_JobNum);
COMMIT;
END;

DBMSJ.OB
PL/SQL LOB DBMSJLOB. , CLOB,
NCLOB, BLOB BFILE. DBMS_LOB LOB, LOB, LOB , LOB, INSTR SUBSTR,

481

LOB . DBMS_LOB BFILE,


, BFILE. OracleSi
DBMS_LOB LOB.
DBMS_LOB LOB. LOB . LOB
EMPTYJBLOB EMPTY_CLOB.

DBMSJLOB:
DBMS_LOB.sql
/* CLOB, p_InputLocator,
* p_ChunkSize . p_0utputLocator. ,
*
* ReverseLOB('abcdefghijklmnopqrstuvwzxyz', output, 4)
* 'yzuvwxqrstmnopijkiefghabcd'. p_ChunkSize
* ,
* LOB, LOB,
* , p_ChunkSize. p_ChunkSize ,
* LOB, LOB
* LOB.
V
CREATE OR REPLACE PROCEDURE ReverseLOB (
p_InputLocator IN CLOB,
p_OutputLocator IN OUT CLOB,
p_ChunkSize IN NUMBER) AS
v_InputOffset
BINARY_INTEGER;
vJMputOffset
BINARY_INTEGER;
v_LOBLength
BINARY_INTEGER;
v_Curr.entCnunkSize BINARY_INTEGER;
eJYimLength
EXCEPTION;
PRAGMA EXCEPTION_INIT(e_TrimLength, -22926);
BEGIN
- LOB.
v_LOBLength := DBMS_LOB.GETLENGTH(p_InputLocator);
- LOB .
- ORA-22926, LOB v_LOBLength.
BEGIN
DBMS_LOB.TRIM(p_OutputLocator, v_LOBLength);
EXCEPTION
WHEN eJYimLength THEN
NULL;
END;

482

12
- .
- , - .
v_InputOffset := 1;
v_0utput0ffset := v_LOBLength + 1;
- LOB LOB.
LOOP
- , ..
- v_InputOffset v_LOBLength.
EXIT WHEN vJnputOffset > v_LOBLength;
- LOB p_ChunkSize,
- . , .
IF (v_LOBLength - v_InputOffset + 1) > p_ChunkSize THEN
v_CurrentChunkSize := p_ChunkSize;
ELSE
v_CurrentChunksize := v_LOBLength - v_InputOffset + 1;
END IF;
- .
vJMputOffset := v_0utput0ffset - v_CurrentChunksize;
- .
DBMS_LOB.COPY(p_OutputLocator,
p_InputLocator,
v_CurrentChunksize,
v_0utput0ffset,
v_InputOffset);
- .
v_InputOffset := v_InputOffset + v_CurrentChunkSize;
END LOOP;
END ReverseLOB;

SQL*Plus ReverseLOB:
|

- DBMS_LOB.sql
SQL> CREATE TABLE lobdemo (

2
key NUMBER;
3 clob_col CLOB;
4 blob_col BLOB);
Table created.

SQL> INSERT INTO lobdemo (key, clob_col)


2 VALUES (1, 'abcdefghijklmnopqrstuvwxyz');
1 row created.
SQL> INSERT INTO lobdemo(key, clob_col)
2 VALUES (2, EMPTY_CLOB());
1 row created.
SQL> INSERT INTO lobdemo(key, clob_col)
2 VALUES (3, EMPTY._CLOB());
1 row created.
SQL> INSERT INTO lobdemo(key, clob_col)


2 VALUES (4, EMPTY_CLOB());
1 row created.
SQL> INSERT INTO lobdemo(key, clob_col)
2 VALUES (5, EMPTY_CLOB());
1 row created.
SQL> INSERT INTO lobdemo(key, clob_col)
2 VALUES (6, EMPTY_CLOB(;
1 row created.
SQL> COMMIT;
Commit complete.
SQL> SELECT key, clob_col
2
FROM lobdemo
3 WHERE key BETWEEN 1 AND 6
4 ORDER BY key;
KEY CLOB COL
1 abcdefghijklmnopqrstuvwxyz
2
3
4
5
6
6 rows selected.
SQL> DECLARE
2 v_Source CLOB;
3 v_Destination CLOB;
4 v_Key NUMBER;
5 CURSOR ^Destinations IS
6
SELECT key, clob_col
7
FROM lobdemo
8
WHERE key BETWEEN 2 and 6
9
FOR UPDATE;
10 BEGIN
11 SELECT clob_col
12
INTO v_Source
13
FROM lobdemo
14
WHERE key = 1;
15
16 - 2 - 6 1
17 - .
18 OPEN ^Destinations;
19 LOOP
20
FETCH c_Destinations INTO v_Key, v_Destination;
21
EXIT WHEN c_Destinations%NOTFOUND;
22
23
IF (v_Key = 2) THEN
24
ReverseLOB(v_Source, v_Destination, 4);
25
ELSIF (v_Key = 3) THEN
26
ReverseLOB(v_Source, v_Destination, 2);

483

484

12

27
28
29

ELSIF (v_Key = 4) THEN


ReverseLOB(v_Source, v_Destination, 1);
ELSIF (v_Key = 5) THEN

30
31

ReverseLOB(v_Source, v_Destination, 10);


ELSIF (v_Key = 6) THEN

32

33

ReverseLQB(v_Source, v_Destination, 30);

END IF;

34
END LOOP;
35
CLOSE ^Destinations;
36
COMMIT;
37 END;
38 /

PL/SQL procedure successfully completed.


SQL> SELECT key, clob_col
2 FROM lobdemo
3 WHERE key BETWEEN 1 AND 6
4 ORDER BY key;
KEY CLOB COL
1 abcdefghijklmnopqrstuvwxyz
2 yzuvwxqrstmnopijklefghabcd
3 yzwxuvstqropmnklijghefcdab
4 zyxwvutsrqponmlkjihgfedcba
5 uvwxyzklmnopqrstabcdefghij
6 abcdefghijklmnopqrstuvwxyz
6 rows selected.

PL/SQL, :
.
PL/SQL . , SQL, , .
DBMS_SQL, DBMS_PIPE, DBMS_ALERT,
UTL_FILE, UTL_TCP, UTL_SMTP, UTL_HTTP, UTLJNADDR,
DBMS JOB DBMS_LOB.

488

,
PL/SQL.


PL/SQL , .
SYS, , , SYS
. , SYS, EXECUTE . catproc.sql,
$ORACLE_HOME/rdbms/admin. Oracle. , ,
catproc. sql.
.
, , .
"Oracle 8 : PL/SQL" (. ""), " Oracle".

DBMS_ALERT
7.3
DBMS_ALERT
, . (alerts) , .. . SIGNAL,
WAITONE WAITANY. ,
REGISTER.
dbms_alert_info.

DBMS_APPLICATION_INFO
7.3
DBMS_APPLICATION_INFO (info)
v$session. , (applications)
. , DBMS_APPLICATION_INFO
module, action
client_info v$session .

489

module . , SQL*Plus 'SQL*Plus'. action


, . ,
action
*. client_info
.
DBMS_APPLICATION_INFO (
SET_SESSION_LONGOPS) v$session_
longop, .

DBMS_AQ
OracleS
DBMS_AQ
,
Oracle/AQ. OracleS Java
Oracle/AQ. AQ
.

DBMS_AQADM
OracleS
DBMS_AQADM
AQ. .

DMBS_AQELM
19
DMBS_AQELM AQ no e-mail HTTP.
, , , e-mail
HTTP.

DBMS_BACKUP_RESTORE
OracleSi 8.1.6

,
Windows NT. UNIX
8.1.6.

DBMS_DDL
7.3

490

DBMS_DDL PL/SQL-
DDL, PL/SQL . SQL, DBMS_DDL .
DBMS_DLL ALTER_COMPILE, , , , ANALYZE_OBJECT,
, .

DBMS_DEBUG
OracleS ( ,
8 )
DBMS_DEBUG PL/SQL
Probe. . DBMS_DEBUG :
, . , DEBUG .

DBMS DEFER
OracleS
DBMS_DEFER .
.

DBMS_DEFER_QUERY
OracleS
DBMS_DEFER_QUERY , DBMS_DEFER.
, DBMS_DEFER_QUERY .

DBMS_DEFER_SYS
OracleS
DBMS_DEFER_SYS , DBMS_DEFER, ,
. .

491

DBMS_DESCRIBE
7.3
DBMS_DESCRJBE DESCRIBE_PROCEDURE.
DESCRIBE_PROCEDURE , . ,
.
Oracle 9 DBMS_METADATA,
, .

DBMS_DISTRIBUTED_TRUST_ADMIN
OracleS
. ,
.
,
. Oracle 9 LDAP .

DBMS_FGA
19
DBMS_FGA . : ADD_POLICY,
; DROP_POLICY, ;
ENABLE_POLICY DISABLE_POLICY, .

DBMS_FLASHBACK

19

DBMS_FLASHBACK .
. (flashback)
(SCN). GET_SYSTEM_CHANGE_NUMBER SCN, ENABLE_AT_TIME ENABLE_AT_SYSTEM_CHANGE_NUMBER
. DISABLE .

492

DBMS_HS
OracleS
DBMS_HS
, , (HS, Heterogeneous Services) Oracle. Oracle HS
SQL , Oracle,
Oracle.

DBMS_HS_PASSTHROUGH
OracleS
DBMS_HS_PASSTHROUGH API , .
, , , ,
DBMS_SQL. DBMS_HS_PASSTHROUGH , Oracle .

DBMSJOT
OracleS
DBMSJOT
ANALYZE , . : BUILD_CHAIN_ROWS_TABLE
BUILD_EXCEPTIONS_TABLE, ,
, , .

DBMS_JAVA
OracleS
DBMSJAVA , Java Oracle, Java. , DBMSJAVA.SET_OUTPUT
System.out , DBMS_OUTPUT.
SQL*Plus.

DBMS_JOB
7.3
DBMSJOB PL/SQL . . (job)
PL/SQL, .

493

, PL/SQL ( 16 ) , . DBMS JOB


.

DBMS_LDAP
OracleSz
DBMS_LDAP API,
LDAP, . , DBMS_LDAP .
catldap. sql.
SSL LDAP.

DBMSJ.IBCACHE
OracleQz
DBMS_LIBCACHE
COMPILE_CURSORS_FROM_REMOTE.
SQL PL/SQL (instance)
. , . , , , .

DBMSJ.OB
OracleS
DBMS_LOB (LOB, Large Object): CLOB, BLOB, NCLOB
BFILE. DBMSJLOB LOB
. LOB , OCI JDBC.

DBMS_LOCK
7.3
DBMS_LOCK (lock). ,
Oracle. ,
. "UL", Oracle.

494

DBMS LOGMNR
OracleSi
DBMS_LOGMNR , Log Miner.
. ,

.
&

DBMS_LOGMNR_CDC_PUBLISH
OracleQj
Oracle (Change Data Capture, CDC)
.
DBMS_LOGMNR_CDC_PUBLISH .

DBMS_LOGMNR_CDC_SUBSCRIBE
OracleQi
Oracle (Change Data Capture, CDC)
.
DBMS_LOGMNR_CDC_SUBSCRIBE , DBMS_LOGMNR_CDC_PUBLISH.

DBMSJLOGMNR_D
OracleSi
DBMS_LOGMNR_D
Log Miner. BUILD, ,
.

DBMS_METADATA
19
DBMS_METADATA , . XML. DBMS_METADATA
DBMS_DESCRIBE.

DBMS_MVIEW (DBMS_SNAPSHOT)
19
DBMS_MVIEW .

495

, .
DBMS_SNAPSHOT DBMS_MVTEW,
,
.

DBMS_OBFUSCATION_TOOLKIT
OracleSz

DBMS^OBFUSCATION_TOOLKIT : DESEncrypt DESDecrypt. , DES.



.

DBMS_ODCI
19

DBMS_ODCI
ESTIMATE_CPU_UNITS.
CPU,
, .

DBMS_OFFLINE_OG
OracleSz

DBMS_OFFLINE_OG
-. DBMS_OFFLJNE_
SNAPSHOT DBMS_REPCAT_INSTANTIATE
.

DBMS_OFFLINE_SNAPSHOT
OracleSz

DBMS_OFFLINE_SNAPSHOT
.
DBMS_OFFLINE_OG DBMS_REPCAT_INSTANTIATE .

DBMS_OLAP
Oracle 8


, Oracle Trace.
.

496

DBMS_ORACLE_TRACE_AGENT
OracleS
DBMS_ORACLE_TRACE_AGENT SET_ORACLE_TRACE_IN_SESSION.

.

DBMS_ORACLE_TRACE_USER
OracleS
DBMS_ORACLE_TRACE_USER SET_ORACLE_TRACE. .

DBMS_OUTLN
19
DBMS_OUTLN , . (stored
outline) , SQL. OracleS i OUTLN_PKG,
OUTLN_PKG OracleQ .

DBMS_OUTLN_EDIT
Otacle9z
DBMS_OUTLN_EDIT
. , DBMS_OUTLN.

DBMS_OUTPUT
7.3
DBMS_OUTPUT ( SQL*Plus Server
Manager) PL/SQL.
PL/SQL. DBMS_OUTPUT

Oracle Reports.

DBMS_PCLXUTIL
OracleS i
. ,
, .

497

DBMS_PIPE
7.3
DBMS_ALERT, DBMS_PIPE
, , . , (pipes), . ,
, .

DBMS_PROFILER
OracleS
DBMS_PROFILER API PL/SQL Profiler,
/ PL/SQL.
.

DBMS_RANDOM
OracleS
DBMS_RANDOM .
, PL/SQL, Oracle.

OracleS DBMS_RANDOM
.
PL/SQL (Cryptographic Toolkit)
catoctk. sgl.
DBMS_CRYPTO_TOOLKIT,
DBMS_RANDOM.

DBMS_RECITIFIER_DIFF
OracleS
DBMS_REPCAT_* .

DBMSJtEDIFINITION
Oracle9i
DBMS_REDIFINITION .
.

498

DBMS_REFRESH
7.8
DBMS_REFRESH ( ), .
, , .

DBMS_REPAIR
OracleSi
DBMS_REPAIR ,
. , , .

DBMS_REPCAT, DBMS_REPCAT_ADMIN,
DBMS_REPCAT_INSTANTIATE,DBMS_REPCAT_RGT
DBMS_REPUTIL
OracleS
Oracle.
. Oracle.

DBMS_REPCAT

DBMS_REPCAT_ADMIN

DBMS_REPCAT_INSTANTIATE

DBMS_REPCAT_RGT


DBMS_REPUTIL

DBMS_RESOURCE_MANAGER
DBMS_RESOURCE_MANAGER_PRIVS
OracleS i

499

, ,
.

DBMS_RESUMABLE
OracleQi
DBMS_RESUMABLE .
,
, .

.

DBMS_RLS
OracleS
DBMS_RLS
. DBMS_RLS , , , . (Enterprise Edition) OracleSz
19.

DBMS_ROWID
OracleS
OracleS ROWID ( ) ,
Oracle?, OracleS ROWID .
DBMS_ROWID
ROWID Oracle? OracleS
ROWID.

DBMS_SESSION
7.3
ALTER SESSION
PL/SQL. DBMS_SESSION ALTER SESSION,
PL/SQL. DBMS_SESSION
SQL, , ALTER SESSION.

DBMS_SHARED_POOL
7.3
DBMS_SHARED_POOL (shared pool).

500

,
. PL/SQL.

DBMS_SPACE DBMS_SPACE_ADMIN
OracleS
DBMS_SPACE
, DBMS_SPACE_ADMIN
.

DBMS_SQL
7.3
DBMS_SQL PL/SQL.
SQL PL/SQL . , DBMS_SQL
PL/SQL DDL. OracleS SQL, , DBMS_SQL.

DBMS_STANDARD STANDARD
7.3
DBMS_STANDARD STANDARD
PL/SQL. ,
.

DBMS_STATS
OracleS
DBMS_STATS ,
.
.

DBMS_TRACE
OracleS
DBMS_TRACE PL/SQL .
PL/SQL ,
, SQL.

DBMSJTRANSACTION
7.3
DBMS_TRANSACTION , .
SQL- PL/SQL. DBMSJTRANSACTION SET TRANSACTION.

DBMS .TRANSFORM
OracleQz
DBMS_TRANSFORM ,
,
Oracle Advanced Quening.

DBMS_TTS
OracleSz
DBMS_TTS .
TRANSPORT_SET_CHECK ,
, DOWNGRADE ,
.

DBMS_TYPES
19
DBMS_TYPES , ,
. interMedia.

DBMS_UTILITY
7.3
DBMSJLJTILITY ,
. DBMS_UTILITY FORMAT_
CALL_STACK FORMAT_ERROR_STACK,
PL/SQL .

DBMS_WM
19
DBMS_WM API Workspace Manager.

502

,
, .

DBMS_XMLQUERY, DBMS_XMLSAVE XMLGEN


19
API XML. XMLGEN SQL
XML, a DBMS_XMLQUERY XMLGEN ,
, PL/SQL. DBMS_XMLSAVE XML
.

DEBUG_EXTPROC
OracleS
DEBUG_EXTPROC . STARTUP_
EXTPROC_AGENT, .
.

SDO_CS, SDO_GEOM, SDE_LRS, SDO_MIGRATE


SDO_TUNE "
19

Oracle.
mdsys, sys.

UTL_COLL
OracleS
UTL_COLL
IS_LOCATOR, ,
.

UTL_ENCODE
19
UTL_ENCODE RAW ,
. : base64,
uuencode quoted printable. e-mail.

503

UTL_FILE
7.3
UTL_FILE PL/SQL /. PL/SQL , ,
. .
UTL_FILE ; .

UTL_HTTP
7.3
UTL_HTTP HTTP-
PL/SQL SQL. Oracle Internet Application Server, web- . UTL_HTTP
: REQUEST REQUEST_PIECES. REQUEST 2000 Web, a
REQUEST_PIECES PL/SQL. OracleS
REQUEST REQUEST_PIECES .

UTLJNADDR
19

UTLJNADDR . : GET_HOST_NAME, IP-; GET_HOST_ADDRESS,


IP- .

UTL_PG
7.3
UTL_PG
COBOL Oracle.
UTL_RAW.

UTL_RAW
7.3
UTL_RAW
RAW
RAW . RAWTOHEX
HEXTORAW STANDARD.

504

UTL_REF
OracleS
UTL_REF
PL/SQL. SQL
. UTL_REF , ,
.

UTL_SMTP
OracleS
UTL_SMTP
SMTP, e-mail. e-mail SMTP,
.

UTLJTCP
OracleS
UTL_TCP TCP,
-. ,
UTL_HTTP UTL_SMTP
UTL_TCP. UTL_TCP .

UTL_URL
19
UTL_URL UTL ( ).
UTL %.

PL/SQL

506

1, , PL/SQL.

( , ..).
SQL, , , .


PL/SQL,
Oracle. 18 19
.
. , 18
19' (, AUTHID NULLIF).
, 19,
, , SQL, (*). ,
, . .
, Oracle, ,
, ,
STANDARD.
ABORT
ALL*
ARRAY
ASSERT
AUTHID
BEGIN
BOOLEAN
CHAR*
CLUSTER*
COLLECT
COMPRESS*
CREATE*
DATABASE
DBA

DECLARE
DELETE*

ACCEPT
ALTER*
ARRAYLEN
ASSIGN
AUTHORIZATION
BETWEEN*
BULK
CHAR.BASE
CLUSTERS
COLUMN*
CONNECT*
CURRENT*
DATABASE
DEBUGOFF
DEFAULT*
DESC*

ACCESS*
AND*
AS*
AT

Average
BINARYJNTEGER
BY*

CHECK*
COALESCE
COMMENT*
CONSTANT
CURRVAL
DATE*
DEBUGON
DEFINITION
DIGITS

ADD*
ANY*
ASC*
AUDIT*
BASEJABLE
BODY
CASE
CLOSE
COLAUTH
COMMIT
CRASH
CURSOR
DAY

DECIMAL*
DELAY
DISPOSE

507

PL/SQL
DISTINCT*

DO

DROP*

ELSE*

ELSIF

END

ENTRY

EXCEPTION

EXCEPTIONJNIT
EXIT

EXCLUSIVE*

EXECUTE

EXISTS*

EXTENDS

EXTRACT

FALSE

FETCH

FILE*

FLOAT*

FOR*

FORALL

FORM*

FROM*

FUNCTION

GENERIC

GOTO

GRANT*

HAVING*

HEAP

HOUR

GROUP*
IDENTIFIED*

IF

IMMEDIATE*

IN*

INCREMENT*

INDEX*

INDEXES

INDICATOR

INITIAL*

INSERT*

INTEGER*

INTERFACE

INTERSECT*

INTERVAL

INTO*

IS*

ISOLATION

JAVA

LEVEL*

LIKE*

LIMITED

LOCK*

LONG*

LOOP

MAX

MAXEXTENTS*

MIN

MINUS*

MINUTE

MLSUBEL*

MOD

MODE*

MONTH

NATURAL

NATURALN

NEW

NEXTVAL

NOAUDIT*

NOCOMPRESS*

NOCOPY

NOT*

NOWAIT*

NULL*

NULLIF

NUMBER*

NUMBER.BASE

OCIROWID

OF*

OFFLINE*

ON*

ONLINE*

OPAQUE

OPEN

OPERATOR

OPTION*

OR*

ORDER*

ORGANIZATION

OTHERS

OUT

PACKAGE

PARTITION

PCTFREE*

PLSJNTEGER

POSITIVE

POSITIVEN

PRAGMA

PRIOR*

PRIVATE

PRIVILEGES*

PROCEDURE

PUBLIC*

RAISE

RANGE

RAW*

REAL

RECORD

REF

RELEASE

REMR

RENAME*

RESOURCE*

RETURN

REVERSE

REVOKE*

ROLLBACK

ROW*

ROWID*

ROWLABEL*

ROWNUM

ROWS*

ROWTYPE

RUN

SAVEPOINT

SCHEMA

SECOND

SELECT*

SEPARATE

SESSION*

SET*

SHARE*

SMALLINT*

SPACE

SQL

SQLCODE

SQLERRM

START*

STATEMENT

STDDEV

SUBTYPE

SUCCESSFUL*

SUM

SYNONYM*

SYSDATE*

TABAUTH
TERMINATE

TABLE*

TABLES*

THEN*

TIME

TASK

508

TIMESTAMP

TIMEZONE.ABBR

TIMEZONE_HOUR

TIMEZONE .MINUTE

TIMEZONE.REGION

TO*

TRIGGER*

TRUE

TYPE

Ul

UID*

UNION*

UNIQUE*

UPDATE*

USE

USER*

VALIDATE*

VALUES*

VARCHAR*

VARCHAR2 *

VARIANCE

VIEW*

VIEWS

WHEN

WHENEVER*

WHERE*

WHILE

WITH*

WORK

WRITE

XOR

YEAR

ZONE

,
. ,
:
)

DECLARE
"BEGIN" NUMBER;
BEGIN
"BEGIN" := 7;
END;

510

, PL/SQL.
, . , .


(data dictionary) , Oracle . ,
, .
, ,
.
Oracle SYS.
, ,
. PL/SQL . catalog.sql,
. Unix catalog.sql $ORACLE_HOME/rdbms/admin. SYS, SQLDBA
H3SQL*Plus.
(
, , v$) "Oracle Sever Reference".


, user_*, all_* dba_*. , :
user_source, all_source dba_source. ,
user_* , ,
al 1_* , ( ), dba_* .
SQL PL/SQL .

( ).
. ,
user_objects object_name, . SQL*Plus
user_objects:

511

SQL> SELECT object_type, status


2
FROM user_objects
3
WHERE object_name = UPPER('ClassPackage');
OBJECT_TYPE
STATUS
PACKAGE

VALID

PACKAGE BODY VALID

UPPER:
( ClassPackage 9).

SYS.
SYS
DBA. , DBA, user_,
all_* . dba_* ,
SELECT .
SYS. . Oracle
(
) . , u0801070.sql
8.1.7 . , catproc. sql.



.
, .
, , LOB
OracleS Oracle9



,
,



512


.
"Oracle Server Reference".
dictionary,
.


,
.
:
,

, -

Oracle,

,
Oracle ,
.

all_clusters

Oracle?

dba_clusters

Oracle?

user clusters

Oracle?

all_cluster_hash_
expressions

Oracle?

dba_cluster_hash_

Oracle?

expressions
user_cluster_hash_ - ,

Oracle?

expressions

dba_clu_columns

Oracle?

user clu columns

Oracle?

513

all_all_tables


. (
)

OracleB

dba_all_tables

( ) Oracle8

user_all_tables

( )

OracleS

all_col_comments

Oracle?

dba_col_comments

Oracle?

user_col_comments

Oracle?

all_partial_
drop_tabs

OracleS/

dba_partial_
drop_tabs

OracleS/

user_partial_
drop_tabs

OracleS/

all_refs

(REF)

OracleS

dba_refs

(REF)
,

OracleS

user_refs

(REF)
OracleS
,

all_tab_columns

Oracle?

dba_tab_columns

Oracle?

user_tab_coluinns

Oracle?

all_tab_comments

Oracle?

dba_tab_comments

Oracle?

user_tab_comments

,
Oracle?

all_tables

Oracle?

dba_tables

Oracle?

user_tables

Oracle?

514

all_unused_
col_tabs

OracleS/

dba_unused_
col_tabs

OracleS/

user_unused_
col_tabs

OracleS/

all_updatable_
columns

OracleS

dba_updatable_
columns

OracleS

user_updatable_
columns

,
,

OracleS

all_views

Oracle?

dba_views

Oracle?

user_views

Oracle?

, LOB,

OracleS
: ,
LOB :


all_coll_types
dba_coll_types
user_coll_types
allvarrays
dba_varrays

,
varray varray
( )
,
varray

OracleS
OracleS
OracleS
OracleS/
OracleS/

515

user_varrays

,
varray

,

,

,
,

LOB,

LOB
LOB,
,

OracleS/

all_nested_tables
dba_nested_tables
user_nested_
tables

all_lobs

dba_lobs
user lobs

all_type_attrs

dba_type_attrs
user_type_attrs

all_type_methods
dba_type_methods
user_type_methods

all__types
dba_types
userjtypes
all_object_tables
dba_object_tables
user_object_tables



,



,

OracleS
OracleS
OracleS

OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS

OracleS/ Oracle?/
, 18 19, :

516






Oracle,


all_context
dba_context

all_dimensions
dba_dimensions
user_dimensions

all_dim_attributes
dba_dim_attributes

user_dim_attributes

all_dim_child_of
dba_dim_child_of
user_dim_crtild_of
all_dim_hierarchies
dba_dim_hierarchies
user_dim_hierarchies
all_dim_join_key
dba_dim_join_key
user_dim_join_key
all_dim_levels
dba_dim_levels

OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/

517

user_dim_levels

OracleS/

all_din_level_key

OracleS/

dba_dim_level_key

OracleS/

user_dim_level_key

OracleS/

all_external_tables ,

dba_external_tables
user_external_tables ,

all_opancillary

OracleQ/
!9/
OracleS/

dba_opancillary

OracleS/

user_opancillary

OracleS/

all_oparguments

!/

OracleS/

dba_oparguments

OracleS/

user_oparguments

OracleS/

all_opbindings

OracleS/'

dba_opbindings
user_opbindings

OracleS/

all_operators

dba_operators

OracleS/'

user_operators

OracleS/'

all_outline_hints

OracleS/

dba_outline_hints
user_outline_hints

,
,

OracleS/
OracleS/

all_outlines

OracleS/

dba_outlines

OracleS/
OracleS/

user_outlines

OracleS/

OracleS/

518

all_policies

OracleS/

dba_policies
user_policies

OracleS/
OracleS/


, ,
.
:






all_jobs

Oracle?


user_jobs
,

dba_jobs_running ,

all_db_links


dba_db_links
,
user_db_links

all_.di rectories
dba_directories


all_libraries
dba_libraries

user_libraries
,

all_sequences

dba_sequences

user_sequences
,
dba_jobs

Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
OracleS
OracleS
OracleS
OracleS
OracleS
Oracle?
Oracle?
Oracle?

519

all_synonyms


Oracle?

Oracle?
, - Oracle?

dba_synonyms
user_synonyms


, OracleS, , .
OracleS ,
LOB.
.


all_part_col_statistics
dba__part_col_statistics
user_part_col_statistics
all_part_histograins
dba_part_histograms
user_part_histograms
all_part_indexes
dba_part_indexes
user_part_indexes
all_part_key_columns
dba_part_key_columns
user_part_key_columns
all_part_lobs
dba_part_lobs
user_part_lobs



LOB
LOB
LOB

OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS
OracleS/
OracleS/
OracleS/

520


all_part_tables
dba_part_tables
user_part_tables



,

all_subpart_col_statistics

dba_subpart_col_statistics
,
user_subpart_col_

statistics

all_subpart_histogra(ns

dba_subpart_histograms
,
user_subpart_histograms

,
all_subpart_key_columns

"/"
dba_subpart_key_columns
,
"/"
user_subpart_key_columns
,
"/"

all_tab_partitions
dba_tab_partitions

user_tab_partitions

all_tab_subpartitions

dba_tab_subpartitions


user_tab_subpartitions
LOB,
all_lob_partitions

dba_lob_partitions
LOB
user_lob_partitions
LOB,

all_lob_subpartitions
LOB,

dba_lob_subpartitions
LOB
user_lob_subpartitions
LOB,

all_ind_partitions


dba_ind_partitions

OracleS
OracleS
Oracle8
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleS
OracleS
OracleS
OracleS/
OracleS/
OracleS/
OracleS/
OracleS/
OracleSi
OracleSi
OracleS/
OracleS/
OracleS
OracleS

521

user_ifid_partitions

OracleS

all_ind_subpartitions
dba_ind_subpartitions
user_ind_subpartitions

OracleS/'
OracleS/
OracleS/

, .
, , ,
Oracle.

all_ind_colLimns







,

,

,

Oracle?
Oracle?
Oracle?
Oracleu'

dba_ind_columns
user_ind_columns
all_ind_expressions
dba_ind_expressions
user_ind_expressions

all_indexes
dba_indexes
user_indexes
all_indextypes
dba_indextypes
user_indextypes
all_indextype_operators
dba_indextype_operators
user_indextype_operators

OracleS/
OracleS/'
Oracle?
Oracle?
Oracle?
OracleS/'
OracleS/
OracleS/
OracleS/'
OracleS/'
OracleS/

522

,

Oracle?, OracleSz
.
, .

,

,

Oracle9/

dba_base_table_
mviews


,

,

19/

user_base_
table mviews

,

,

19/

all_mview_
aggregates

OracleS/

dba_mview_
aggregates

OracleS/

user_mview_
aggregates

OracleB/

all_mview_analysis
.

OracleS/

all_base_table_

mviews

dba_mview_analysis OracleS/'

user_mview_analysis


OracleS/

all_mview_detail relations


(
) FROM

OracleS/

523

dba_mview_detail_
relations


OracleS/
(
) FROM

user_mview_detail_
relations


OracleS/
(
) FROM

all_mview_joins

OracleS/
WHERE

dba_mview_joins


WHERE

user_mview_joins

OracleS/
WHERE

all_mview_keys

GROUP BY

OracleS/'

dba_mview_keys

GROUP BY

OracleS/

user_mview_keys

GROUP BY

OracleS/

alljnyiews

OracleS/

dbajnviews

OracleS/

user_mviews

OracleS/

all_refresh

OracleS

dba_refresh

OracleS

user_ref resh

OracleS

all_refresh_
children

OracleS

dba_ref resh__
children

OracleS

OracleS/

524

user_ref resh_
children

18

all_ref resh_
dependencies

OracleS/

all_registered_
snapshots

OracleS

dba_registered_
snapshots

OracleS

user_registered_
snapshots

OracleS

all_snapshot_logs

OracleS

dba_snapshot_logs

OracleS

user_snapshot_logs

OracleS

all_snapshot_refresh_times

OracleS

dba_snapshot_refresh_times

OracleS

user_snapshot_refresh_times

OracleS

all_snapshots

Oracle?

dba_snapshots

Oracle?

user_snapshpts

Oracle?

all_summaries

OracleS/

dba_summaries

OracleS/

user_summaries

OracleS/

,
, ( ),
.

525

all_arguments


( )

Oracle?

user_arguments


( )

Oracle?

all_method_
pa rams

OracleS

dbajnethocL
pa rams

OracleS

user_method_
pa rams

OracleS

all_method_
results

OracleS

dba_method_
results

OracleS

user_method_
results

OracleS

all_internal_
triggers

OracleS/

dba_internal_
triggers

OracleS/

user_internal_
triggers

OracleS/

all_triggers

Oracle?

dba_triggers

Oracle?

user_triggers

Oracle?

all_trigger_cols

Oracle?

dba_trigger_cols , Oracle?
user_trigger_
cols

,
,

Oracle?


, . *_t riggers (. ).

526


all_er rs
dba_errors
user_errors
all_sou rce
dba_source
user_sou rce

,
, , , ,
,
, ,
, , , ,
.
, ,
, , , ,

,
, , ,

, ,
, ,
, ,
, ,

Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?

all_dependencies

Oracle?

dba_dependencies
user_dependencies

all_cons_columns
dba_cons_columns
user_cons_columns
all_constraints
dba_constraints
user constraints

Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?
Oracle?

527

all_associations

OracleS/

dba_associations

OracleS/

user_associations

OracleS/

all_ustats

OracleS/

dba_ustats

OracleS/

user_ustats

OracleS/

all_tab_col_
statistics

OracleS

dba_tab_col_
statistics

OracleS

user_tab_col_
statistics
all_tab_histograms

OracleS

dba_tab_histograms

use r_tab_.histog rams


OracleS
OracleS
OracleS

all_def_aijdit_opts

Oracle?

audit actions

Oracle?

, ,
.


,
PUBLIC

Oracle?

all_col_privs

528

dba_col_privs

Oracle?

user_col_p'rivs


,
,

Oracle?

all_col_privs_
made

Oracle?

user_col_privs_
made
all_col_privs_
reed

Oracle?


Oracle?
,
PUBLIC

user_col_privs_
Oracle?
reed
,

all_tab_privs

,
PUBUC

pracle?

dba_tab_privs

Oracle?

user_tab_.privs

,
,

Oracle?

all_tab_privs_
made

Oracle?

user_tab_privs_
made
all_tab_privs_
reed
user_tab_privs_
reed
dba_sys_privs

Oracle?

,
PUBLIC

Oracle?

Oracle?

Oracle?

Oracle?

user_sys_privs

ORACLG

ORACLE9/
Oracle
7.x, 8/ 9/
,
Oraple, PL/SQL.

. ,
PL/SQL
.


Oracle Press

Web-
OraclePressBooks.com

:

PL/SQL

PL/SQL, ,
, ,



SQL



SQL



OracleQi

,
DML,


PL/SQL,
,
SQL

D S RN
REQUIRED READING ', information Age

""
www.lory-press.ru