You are on page 1of 104

SQL v PL/SQL

C bn

Oracle c bn - SQL v PL/SQL

MC LC
MC LC ... CHNG 1. GII THIU CHUNG ...
1.1. NGN NG SQL ... 1.1.1. Lch s pht trin ca ngn ng SQL ... 1.1.2. Chun SQL ... 1.2. CC KHI NIM C BN TRONG C S D LIU ... 1.2.1. Cc thnh phn logic trong database... 1.2.2. Cc i tng trong database ... 1.2.3. Cc nhm lnh SQL c bn ... 1.3. C S D LIU THC HNH... 1.3.1. M hnh d liu ... 1.3.2. Cu trc bng d liu ...

...1 ...5
..5 .5 ..5 ...5 ..5 ...6 .6 ..7 ..7 .7

CHNG 2. LNH TRUY VN C BN ...


2.1. CU LNH TRUY VN ... 2.1.1. Quy tc vit lnh ... 2.1.2. Cu lnh truy vn c bn ... 2.1.3. Cc thnh phn khc ca mnh SELECT ... 2.1.4. Phn bit gi tr d liu tr v ... 2.1.5. Gi tr NULL ... 2.2. SQL*PLUS, CNG C TNG TC LNH SQL VI DATABASE ... 2.2.1. Cu lnh tng tc ca SQL*Plus ... 2.2.2. Phn nhm cu lnh trong SQL*Plus... 2.2.3. Chi tit cc lnh SQL*Plus c bn ... 2.3. BI TP ...

.9
..9 ...9 ..9 ..9 ..10 ..11 ...11 .11 ...12 .13 ..15

CHNG 3. TRUY VN D LIU C IU KIN ...


3.1. CC GII HN TRONG TRUY VN D LIU ... 3.1.1. Mnh WHERE... 3.1.2. Cc ton t s dng trong mnh WHERE ... 3.1.3. V d s dng cc ton t iu kin ... 3.2. SP XP D LIU TR V... 3.2.1. Mnh ORDER BY ... 3.2.2. Sp xp nhiu ct d liu tr v... 3.3. BI TP ...

..17
...17 ...17 ..18 .19 ..20 ...20 ..20 ..21

CHNG 4. CC HM SQL ...


4.1. TNG QUAN V HM SQL... 4.1.1. Cu trc hm SQL ... 4.1.2. Phn loi hm SQL ... 4.2. HM SQL THAO TC TRN TNG DNG D LIU... 4.2.1. Cc hm thao tc trn kiu d liu s... 4.2.2. Cc hm thao tc trn kiu d liu k t... 4.2.3. Cc hm thao tc trn kiu d liu thi gian... 4.2.4. Cc hm chuyn i kiu ... 4.3. HM THAO TC TRN TP HP ... 4.3.1. Cc hm tc ng trn nhm ... 4.3.2. Mnh GROUP BY ... 4.4. MT S HM MI B SUNG TRONG Oracle9i ... 4.4.1. Hm NULLIF ... 4.4.2. Hm COALSCE ... 4.4.3. Cu lnh case ...

...23
..23 .23 ...23 .24 ..24 .26 .30 ...32 ...34 ...34 ...35 ..36 .36 ..36 ..36 Trang 1

Oracle c bn - SQL v PL/SQL 4.5. BI TP ... 4.5.1. Hm trn tng dng d liu ... 4.5.2. Hm trn nhm d liu ... ..36 ..36 ...39

CHNG 5. LNH TRUY VN D LIU M RNG...


5.1. KT HP D LIU T NHIU BNG ... 5.1.1. Mi lin kt tng ng ... 5.1.2. Mi lin kt khng tng ng ... 5.1.3. Mi lin kt cng ... 5.1.4. Lin kt ca bng vi chnh n (t thn)... 5.1.5. Cch biu din kt ni mi trong Oracle 9i ... 5.1.6. Cc ton t tp hp ... 5.2. LNH TRUY VN LNG ... 5.2.1. Cu lnh SELECT lng nhau. .. 5.2.2. Ton t SOME/ANY/ALL/NOT IN/EXITS ... 5.3. CU TRC HNH CY ... 5.3.1. Cu trc hnh cy trong 1 table ... 5.3.2. K thut thc hin ... 5.3.3. Mnh WHERE trong cu trc hnh cy... 5.4. BI TP ...

.40
...40 ..40 .40 .40 .41 ...41 ..42 ...43 ...43 ..43 .44 ...44 ..44 ..45 ..46

CHNG 6. BIN RUNTIME ...


6.1. D LIU THAY TH TRONG CU LNH ... 6.2. LNH DEFINE ... 6.3. LNH ACCEPT ... 6.4. BI TP ...

...50
.50 ..50 ...51 ..51

CHNG 7. TABLE V CC LNH SQL V TABLE...


7.1. LNH TO TABLE... 7.1.1. C php to bng ... 7.1.2. Tnh ton kch thc table (tham kho) ... 7.2. MT S QUY TC KHI TO TABLE ... 7.2.1. Quy tc t tn Object ... 7.2.2. Quy tc khi tham chiu n Object ... 7.3. Cc Kiu d liu c bn... 7.3.1. Kiu CHAR ... 7.3.2. Kiu VARCHAR2 ... 7.3.3. Kiu VARCHAR ... 7.3.4. Kiu NUMBER ... 7.3.5. Kiu FLOAT ... 7.3.6. Kiu LONG ... 7.3.7. Kiu DATE ... 7.3.8. Kiu RAW v kiu LONG RAW... 7.3.9. Kiu ROWID ... 7.3.10. Kiu MLSLABEL ... 7.3.11. Chuyn i kiu ... 7.4. RNG BUC D LIU TRONG TABLE ... 7.4.1. NULL/NOT NULL ... 7.4.2. UNIQUE ... 7.4.3. PRIMARY KEY ... 7.4.4. FOREIGN KEY ( Referential ) ... 7.4.5. CHECK ... 7.5. LNH DDL CAN THIP TI TABLE ... 7.5.1. Chnh sa cu trc table ... 7.5.2. Cc lnh DDL khc ... 7.5.3. Ch dn cho table ... 7.5.4. Thay i tn object... 7.5.5. Xa d liu ca table ...

...52
52 52 53 54 54 54 55 55 55 56 56 56 56 57 58 58 58 58 59 59 59 59 60 60 60 60 61 61 62 62

Trang 2

Oracle c bn - SQL v PL/SQL 7.6. THNG TIN V TABLE TRONG T IN D LIU... 7.7. BI TP ... ...62 ..63

CHNG 8. CC LNH THAO TC D LIU...


8.1. THAO TC D LIU TRONG TABLE ... 8.1.1. Thm mi dng d liu ... 8.1.2. Cp nht dng d liu ... 8.1.3. Lnh Merge... 8.1.4. Xa dng d liu... 8.1.5. Li rng buc d liu ... 8.2. LNH IU KHIN GIAO DCH... 8.3. BI TP ...

..64
.64 ...64 .65 ...65 .66 ...66 ..66 ..67

CHNG 9. SEQUENCE V INDEX...


9.1. SEQUENCE... 9.1.1. To Sequence... 9.1.2. Thay i v hu sequence ... 9.2. INDEX... 9.2.1. To index ... 9.2.2. S dng index... 9.3. BI TP ...

...68
...68 ..68 .69 ...69 ...69 ..69 ..70

CHNG 10. VIEWS ...


10.1. VIEWS ... 10.1.1. To view ... 10.1.2. Xa cc view ... 10.2. BI TP ...

...71
...71 ..71 ..71 ...72

CHNG 11. QUYN V BO MT ...


11.1. QUYN - PRIVILEGE ... 11.2. ROLE... 11.3. SYNONYM...

..73
.73 ..74 ...74

CHNG 12. GII THIU NGN NG PL/SQL...


12.1. TNG QUAN V PL/SQL ... 12.1.1. C php lnh PL/SQL ... 12.1.2. Khi lnh PL/SQL ... 12.2. LNH LP TRNH PL/SQL N GIN ... 12.2.1. Lnh IF... 12.2.2. Lnh lp LOOP khng nh trc ... 12.2.3. Lnh lp LOOP c nh trc ... 12.2.4. Lnh lp WHILE ... 12.2.5. Lnh GOTO, nhy v iu kin ... 12.3. GII THIU CURSOR ... 12.4. CC KIU D LIU THNG DNG... 12.4.1. Kiu d liu Table ... 12.4.2. Kiu d liu Record ... 12.4.3. Sao kiu d liu mt dng ... 12.4.4. Sao kiu d liu ca mt ct ... 12.4.5. Lnh SELECT... INTO... 12.5. BI TP ...

..76
...76 ...76 ...76 ...77 ..77 ...78 ...78 ...78 .78 ...79 ..81 ...81 ...81 ..82 ..82 ...82 ...83

CHNG 13. GII THIU PROCEDURE BUILDER ...


13.1. CC THNH PHN TRONG PROCEDURE BUILDER ... 13.1.1. Object Navigator ... 13.1.2. Program Unit Editor... 13.1.3. Store Program Unit Editor ...

..84
...84 ..84 .85 ...85 Trang 3

Oracle c bn - SQL v PL/SQL 13.1.4. Database Trigger Edditor ... 13.2. CC HM, TH TC ... 13.2.1. To hm, th tc trn Client ... 13.2.2. To hm, th tc trn Server ... 13.2.3. D li i vi cc hm, th tc ... .85 .86 ...86 .86 ..87

CHNG 14. GII THIU CC TH TC, HM V PACKAGE ...


14.1. TH TC ... 14.1.1. To th tc ... 14.1.2. Hu b th tc ... 14.1.3. Cc bc lu gi mt th tc ... 14.2. HM ... 14.2.1. To hm... 14.2.2. Thc hin mt hm ... 14.2.3. Li ch ca vic s dng hm ... 14.2.4. Mt s hn ch khi s dng hm trong cu lnh SQL ... 14.2.5. Hu b hm... 14.2.6. Hm v th tc ... 14.3. PACKAGE... 14.3.1. Cu trc ca package ... 14.3.2. To package ... 14.3.3. Hu package ... 14.3.4. Li ch ca vic s dng package ... 14.3.5. Mt s package chun ca Oracle ...

...88
..88 ..88 ...89 ...89 ...89 ...90 .90 ...91 ..91 .91 ..92 ...92 ...92 ..93 ..95 ..95 ..96

CHNG 15. DATABASE TRIGGER ...


15.1. TO TRIGGER ... 15.1.1. Phn loi trigger ... 15.1.2. Lnh to trigger ... 15.1.3. S dng Procedure builder to trigger ... 15.2. QUN L TRIGGER ... 15.2.1. Phn bit database trigger ... 15.2.2. Thay i trng thi ca database trigger ... 15.2.3. Hu b trigger ... 15.2.4. Lu khi s dng trigger ...

.97
..97 ...97 .98 ...99 ...100 ...100 ...101 .101 ..102

PH LC ...
A - TI LIU THAM KHO ... B - DANH MC CC HNH V...

...103
.103 ..103

Trang 4

Oracle c bn - SQL v PL/SQL

Chng 1. GII THIU CHUNG


1.1.NGN NG SQL
1.1.1. Lch s pht trin ca ngn ng SQL
M hnh c s d liu (CSDL) quan h - RDBMS, do E.F Codd a ra vo u thp k 70. T n nay, n lin tc pht trin tr thnh m hnh CSDL ph bin bc nht. M hnh quan h gm cc thnh phn sau: Tp hp cc i tng v / hoc cc mi quan h Tp hp cc x l tc ng ti cc quan h Rng buc d liu m bo tnh chnh xc v nht qun. SQL (Structured Query Language, c l "sequel") l tp lnh truy xut CSDL quan h. Ngn ng SQL c IBM s dng u tin trong h qun tr CSDL System R vo gia nhng nm 70. H ngn ng SQL u tin (SEQUEL2) c IBM cng b vo thng 11 nm 1976. Nm 1979, tp on Oracle gii thiu thng phm u tin ca SQL. SQL cng c ci t trong cc h qun tr CSDL nh DB2 ca IBM v SQL/DS. Ngy nay, SQL c s dng rng ri v uc xem l ngn ng chun truy cp CSDL quan h.

1.1.2. Chun SQL


Nm 1989, vin tiu chun quc gia Hoa K (ANSI) cng nhn SQL l ngn ng chun truy cp CSDL quan h trong vn bn ANSI SQL89. Nm 1989, t chc tiu chun quc t (ISO) cng nhn SQL ngn ng chun truy cp CSDL quan h trong vn bn ISO 9075-1989. Tt c cc h qun tr CSDL ln trn th gii cho php truy cp bng SQL v hu ht theo chun ANSI.

1.2.CC KHI NIM C BN TRONG C S D LIU


1.2.1. Cc thnh phn logic trong database
Thnh phn Table Row Column Din gii Cu trc lu tr c bn nht trong CSDL quan h (RDBMS), n bao gm 1 hoc nhiu columns (ct d liu) vi 0 hoc nhiu rows (dng d liu). T hp nhng gi tr ca Column trong bng. Mt row cn c gi l 1 record (bn ghi). Quy nh mt loi d liu trong bng. V d: loi d liu tn phng ban c trong bng phng ban. Ta th hin th column ny thng qua tn column v c th km theo mt vi thng tin khc v column nh kiu d liu, di ca d liu. Giao ca column v row. Field chnh l ni cha d liu. Nu khng c d liu trong field ta ni field c gia tr l NULL. L mt column hoc mt tp cc column xc nh tnh duy nht ca cc rows trong bng. V d DEPTNO l Primary Key ca bng DEPT v n c dng xc nh duy nht mt phng ban trong bng DEPT m i din l mt row d liu.

Field Primary Key

Trang 5

Oracle c bn - SQL v PL/SQL

Primary Key nht thit phi c s liu. Foreign Key L mt column hoc mt tp cc columns c tham chiu ti chnh bng hoc mt bng khc. Foreign Key xc nh mi quan h gia cc bng. L cc rng buc i vi d liu trong cc bng thuc database. V d: Foreign Key, Primary Key...

Constraints

V d: minh ho cc thnh phn logic trong database EMP EMPNO 7369 Row 7499 7521 7566 7654 7698 7782 Column
Hnh v 1. Minh ho cc thnh phn logic trong database

DEPT ENAME SMITH ALLEN WARD JONES MARTIN BLAKE CLARK


EMP DEPT

DEPTNO

DEPTNO 10 20 30 40

DNAME ACCOUNTING RESEARCH SALES OPERATIONS Foreign key

20 30 30 20 30 30 10

Primary key

1.2.2. Cc i tng trong database


i tng Table View Sequence Index Synonym Program unit Din gii Cu trc lu tr c bn nht trong CSDL quan h (RDBMS), gm row v column L cu trc logic hin th d liu t 1 hoc nhiu bng Lt sinh gi tr cho cc primary key Tng tnh thc thi cho cu lnh truy vn Tn tng ng ca i tng Tp hp cc cu lnh thc hin c vit bi ngn ng SQL v PL/SQL, bao gm Procedure, function, package...

1.2.3. Cc nhm lnh SQL c bn


Tn lnh
SELECT INSERT UPDATE DELETE

Din gii L lnh thng dng nht, dng ly, xem d liu trong CSDL. L 3 lnh dng nhp thm nhng row mi, thay i ni dung d liu trn cc row hay xo cc row trong table. Nhng lnh ny c gi l cc lnh thao tc d liu DML (Data Manipulation Language)

Trang 6

Oracle c bn - SQL v PL/SQL CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVE POINT GRANT REVOKE

L 3 lnh dng thit lp, thay i hay xo b cu trc d liu nh l table, view, index. Nhng lnh ny c gi l cc lnh nh ngha d liu DDL (Data Definition Language) Qun l vic thay i d liu bng cc lnh DML. Vic thay i d liu c th c nhm li thnh cc transaction. 2 lnh ny dng gn hoc hu cc quyn truy nhp vo CSDL Oracle v cc cu trc bn trong n. Nhng lnh ny c gi l cc lnh iu khin d liu DCL (Data Control Language)

1.3.C S D LIU THC HNH


1.3.1. M hnh d liu

DEPT

EMP

SALGRADE

DUMMY
Hnh v 2. M hnh d liu thc hnh

BONUS

1.3.2. Cu trc bng d liu


Bng DEPT Tn ct
DEPTNO DNAME LOC

Kiu
NUMBER(2) VARCHAR2(14) VARCHAR2(13)

iu kin
PRIMARY KEY

Din gii M phng ban Tn phng ban a ch

Bng SALGRADE Tn ct
GRADE LOSAL HISAL

Kiu
NUMBER NUMBER NUMBER

iu kin
PRIMARY KEY

Din gii Mc lng Gi tr thp nht Gi tr cao nht

Trang 7

Oracle c bn - SQL v PL/SQL

Bng EMP Tn ct
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Kiu
NUMBER(4) VARCHAR2(10) VARCHAR2 (9) NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2) NOT NULL,

iu kin
PRIMARY KEY

Din gii M nhn vin Tn nhn vin Ngh nghip

FOREIGN KEY (EMP.EMPNO)

M ngi qun l Ngy gia nhp cng ty Lng Thng

FOREIGN KEY (DEPT.DEPTNO)

M phng ban

Trang 8

Oracle c bn - SQL v PL/SQL

Chng 2. LNH TRUY VN C BN


2.1.CU LNH TRUY VN
2.1.1. Quy tc vit lnh
Cc cu lnh truy vn c biu din theo cc quy tc sau: Cc lnh trong cu lnh SQL thuc loi khng phn bit ch vit hoa hay thng. Ni dung ca mt cu lnh SQL c th c tri di trn nhiu dng. Cc t kho khng c php vit tt hay phn cch trn nhiu dng Cc mnh thng thng c t trn nhiu dng khc nhau r rng trong vic th hin cu lnh, ta nn s dng cc du TAB khi vit lnh Ta c th s dng cc k t c bit nh: +, -, \, *,... biu din gi tr trong cu lnh. Lnh kt thc bi du chm phy (;).

2.1.2. Cu lnh truy vn c bn


C php:
SELECT FROM [DISTINCT ] table; {*, column [alias],...}

Vi:
SELECT DISTINCT column alias FROM table Hin th ni dung ca mt hay nhiu ct Phn bit ni dung gia cc dng d liu tr v Ly tt cc cc ct trong bng Tn ct d liu cn tr v Phn tiu ca ct d liu tr v Tn bng cha d liu truy vn

V d:
SELECT FROM emp;

Cu trc ca lnh truy vn gm c hai phn: Mnh chn la bao gm Lnh SELECT v tn ct d liu tr v Mnh biu din ni cha bao gm FROM v tn bng.

2.1.3. Cc thnh phn khc ca mnh SELECT Trong mnh SELECT


cn c th a vo cc thnh phn khc: Biu thc ton hc Column alias Cc column c ghp chui Literal Biu thc ton hc Trong mnh SELECT biu thc ton hc c th cc gi tr (column hoc hng s), cc ton t, cc hm. Cc ton t c dng l (+), (-), (*), (/). u tin ca cc ton t ging trong phn s hc. V d:
Trang 9

Oracle c bn - SQL v PL/SQL SELECT ename, sal *12, comm FROM SELECT ename, (sal+250)*12 FROM emp; emp;

Tiu ca ct (column alias) Trong mnh SELECT, column alias l phn nhn hin th ca column khi ly s liu ra. Trong column alias khng c c du cch v vit cch sau tn column mt du cch. Column alias c chp nhn c du cch khi c t trong du nhy kp ( ). V d: (ANUAL chnh l column alias)
SELECT ename, SAL*12 ANUAL, comm FROM emp;

Ghp tip cc ct d liu Ton t ghp tip chui (||) cho php ghp tip d liu trong cc ct khc nhau ca cng mt dng d liu vi nhau thnh mt chui. Ta c th c nhiu ton t ghp chui trong cng mt column alias. V d:
SELECT empno||ename EMPLOYEE FROM emp;

Ghp tip chui k t Trong mnh SELECT, ta c th thc hin ghp tip bt k k t no, biu thc hay s no m khng phi l column hoc column alias. V d:
SELECT empno || ename || WORK IN DEPARTMENT || deptno Employee Detail FROM emp;

2.1.4. Phn bit gi tr d liu tr v


Trong thc t nhiu khi gi tr d liu trn cc dng d liu kt xut trng nhau. Gy nhiu bt tin. c th ly c ch cc dng d liu phn bit vi nhau. Ta s dng mnh DISTINCT trong cu lnh truy vn. V d:
SQL> SELECT deoptno FROM dept; DEPTNO 10 30 10 20 14 rows selected. SQL> SELECT DEPTNO DISTINCT deoptno FROM dept;

10 30 20 3 rows selected.

Trang 10

Oracle c bn - SQL v PL/SQL

2.1.5. Gi tr NULL
Ct c gi tr rng (NULL) l ct cha c gn gi tr, ni cch khc n cha c khi to gi tr. Cc ct vi bt c kiu d liu no cng c th c tr NULL, tr khi c n l kha hay c rng buc ton vn NOT NULL. Trong biu thc c bt k gi tr NULL no kt qu cng l NULL. V d:
SELECT ename, FROM emp; sal*12 + comm ANUAL_SAL

NULL trong cc hm ca SQL Trong cc hm lm vic vi tng ct hay hm v hng (scalar function). Cc hm loi ny tr v tr null khi c tham s NULL, tr hm NVL v TRANSLATE c th tr v gi tr thc. C php ca hm NVL:
NVL (DATECOLUMN,01-01-2001) NVL(NUMBERCOLUMN, 9) NVL(CHARCOLUMN,STRING) NVL(comm,0) tr v tr 0 khi comm l null SELECT ename, sal*12 + NVL(comm,0) ANUAL_SAL FROM emp;

Trong cc hm lm vic vi nhm cc ct (group function): Hu ht cc hm lm vic trn nhm b qua tr null, v d nh khi s dng hm AVG tnh trung bnh cho mt ct c cc gi tr 1000, NULL, NULL, NULL, 2000. Khi trung bnh c tnh l (1000+2000)/2=1500, nh vy tr null b b qua ch khng phi xem l tr 0.

NULL trong cc biu thc so snh, iu kin kim tra c phi NULL hay khng dng cc ton t IS NULL hoc IS NOT NULL. Nu trong biu thc so snh c tr null tham gia v kt qu ca biu thc ph thuc vo tr null th kt qu l khng xc nh, tuy nhin trong biu thc DECODE, hai gi tr null c xem l bng nhau trong php so snh. Oracle xem cc biu thc vi kt qu khng xc nh tng ng vi FALSE. (V d: comm = NULL) c kt qu khng xc nh v do biu thc so snh xem nh cho kt qu FALSE. Trong cu lnh sau khng c mu tin no c chn
SELECT * FROM emp WHERE comm=NULL;

Nu mun chn cc nhn vin c comm l NULL th phi dng ton t IS NULL
SELECT * FROM emp WHERE comm IS NULL;

2.2.SQL*PLUS, CNG C TNG TC LNH SQL VI DATABASE


2.2.1. Cu lnh tng tc ca SQL*Plus
Oracle h tr cng c SQL*Plus cho php ngi s dng c th tng tc trc tip vi Oracle Server thng qua cc cu lnh SQL v PL/SQL. Theo ngi s dng c th tng tc vi Oracle Server thng qua hai loi cu lnh: Cu lnh SQL Cu lnh ca bn thn chng trnh SQL*Plus
Trang 11

Oracle c bn - SQL v PL/SQL

Hnh v 3. Cu lnh ca SQL*Plus

Khc bit gia lnh SQL v SQL*Plus SQL L ngn ng giao tip vi Oracle Server trong vic truy xut d liu Cu lnh da trn b k t chun ASCII Thao tc trn cc d liu c trong cc bng c nh ngha trong database Cu lnh c np vo b nh m trn mt hoc nhiu dng Cu lnh khng c vit tt S dng cc hm trong vic nh dng d liu SQL*Plus Nhn dng lnh SQL v gi lnh ln Server Tu thuc vo tng phin bn ca Oracle Khng thao tc vi d liu trong database Cu lnh c ti trc tip khng thng qua b m Cu lnh c th vit tt

C s dng k t kt thc lnh khi thc hin Khng i hi phi c k t kt thc lnh S dng cc lnh nh dng d liu ca chnh SQL*Plus

2.2.2. Phn nhm cu lnh trong SQL*Plus


Cc lnh SQL*Plus c th phn thnh nhm chnh sau: Nhm lnh Mi trng nh dng d liu Thao tc file Thc hin lnh Son tho Din gii Tc ng v gy nh hng ti mi trng lm vic ca SQL*Plus trong phin lm vic hin ti. nh dng li d liu tr v t server Lu gi, np v chy cc file scrips Gi cc lnh SQL c trong b m ln server Sa i li lnh SQL c trong b m
Trang 12

Oracle c bn - SQL v PL/SQL

Tng tc Cc lnh khc

Cho php ngi dng c th to cc bin s dng trong cu lnh SQL v thao tc vi cc bin nh: nhp d liu, kt xut d liu. Cc lnh khc cho php kt ni ti c s d liu v hin th cc ct d liu theo nh nh dng.

2.2.3. Chi tit cc lnh SQL*Plus c bn


Kt ni ti CSDL C php:
Conn[ect] <user_name>/<password>[@<database>];

Vi:
user_name password database Tn truy nhp Mt khu truy nhp Tn database truy nhp

V d:
Conn Tester/tester@DB1;

Hin th cu trc bng d liu C php:


Desc[ribe] <table_name>;

Vi:
table_name Tn bng cn hin th cu trc

V d:
Desc Name DEPTNO DNAME LOC Dept; Null? NOT NULL Type NUMBER(2) VARCHAR2(14) VARCHAR2(13)

Lnh son tho Tn lnh


A[PPEND] text C[HANGE] /old/new C[HANGE] /text/ CL[EAR] BUFF[ER] DEL DEL n DEL m n I[NPUT] I[NPUT] text L[IST]

Din gii a thm on text vo dng hin ti Chuyn on text c thnh on text mi trong dng hin ti Xo on text trong dng hin ti Xo tt c cc dng trong SQL buffer Xo dng hin ti Xo dng n Xo dng t m n n Thm mt s dng nht nh Thm dng c cha text Lit k ton b cc dng trong SQL buffer

Trang 13

Oracle c bn - SQL v PL/SQL L[IST] n L[IST] m n R[UN] N N text 0 text

Lit k dng n Lit k dng m n n Hin th v chy lnh trong buffer Nhy n dng n Thay dng n bi on text Chn 1 dng trc dng 1

Lnh thao tc file Tn lnh


SAVE filename [.ext] [REP[LACE]|APP[END]] GET filename [.ext] STA[RT] filename [.ext] @ filename [.ext] ED[IT]

Din gii Ghi ni dung bufer thnh file. APPEND ghi thm vo file. REPLACE chn ln ni dung file c. Ghi ni dung file vo buffer. Mc nh phn ui l .sql Chy cc lnh trong file Ging lnh Start Son tho ni dung bufffer c tn l afiedt.buf chy ni dung buffer dng lnh / Son tho ni dung file Ct kt qu hin th trn mn hnh ra file. Vd:
SPOOL result.sql SPOOL OFF

ED[IT]filename [.ext ] SPO[OL] filename [.ext ] [OFF|OUT]

EXIT

Thot khi SQL*Plus

Lnh nh dng ct d liu C php:


COLUMN [{column | alias} [option]]

Tn lnh
CLE[AR] FOR[MAT] format HEA[DING] text JUS[TIFY] align NOPRI[NT] NUL[L] text PRI[NT} TRU[NCATED] WRA[PPED]

Din gii Xo nh dng ca column Chuyn nh dng ca ct d liu t nhn co column Cn tri - left , phi - right, gia - center cho nhn n column Hin th text nu gi tr ca column l NULL Hin th column Xo chui ti cui dng u tin khi hin th Ph cui chui ca dng tip theo

V d 1: Chnh nh dng v nhn ca column


Trang 14

Oracle c bn - SQL v PL/SQL COLUMN ename HEADING Employee|Name FORMAT A15 COLUMN sal JUSTIFY LEFT FORMAT $ 99,990.00 COLUMN hiredate FORMAT A9 NULL Not hired

V d 2: Hin th nh dng hin ti ca column


COLUMN COLUMN ename

V d 3: Xo nh dng hin ti ca column


COLUMN ename CLEAR CLEAR COLUMN

Cc loi nh dng nh dng An 9 0 Din gii Hin th di nht n k t dng cho cc column dng k t hoc dng ngy Hin th s, khng bao gm s 0 Hin th c s 0 $Hin thi $ L Hin th k t L Hin th du thp phn , Hin th du phn chia hng nghn 999999 099999 $9999 L9999 9999.99 9,999 1234 01234 $1234 L1234 1234.00 1,234 V d Kt qu

2.3.BI TP
1. Chn ton b thng tin trong bng SALGRADE GRADE LOSAL HISAL 1 2 3 4 5 700 1201 1401 2001 3001 1200 1400 2000 3000 9999

2. Chn ton b thng tin trong bng EMP EMPNO ENAME JOB MGR HIREDATE 7839 7698 7782 7566 7654 7499 7844 7900 7521 7902 7369 7788 7876 7934 KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER PRESIDENT MANAGER MANAGER MANAGER SALESMAN SALESMAN SALESMAN CLERK SALESMAN ANALYST CLERK ANALYST CLERK CLERK 7839 7839 7839 7698 7698 7698 7698 7698 7566 7902 7566 7788 7782 17-11-1981 01-05-1981 09-06-1981 02-04-1981 28-09-1981 20-02-1981 08-09-1981 03-12-1981 22-02-1981 03-12-1981 17-12-1980 09-12-1982 12-01-1983 23-01-1982

SAL COMM 5000 2850 2450 2975 1250 1600 1500 950 1250 3000 800 3000 1100 1300

DEPTNO 10 30 10 20 30 30 30 30 30 20 20 20 20 10

1400 300 0 500

Trang 15

Oracle c bn - SQL v PL/SQL 3. Hin th mi loi ngh nghip JOB ANALYST CLERK MANAGER PRESIDENT SALESMAN

4. Hin th tn nhn vin v thu nhp trong mt nm (REMUNERATION) ENAME REMUNERATION KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER 14 rows selected. 60000 34200 29400 35700 16400 19500 18000 11400 15500 36000 9600 36000 13200 15600

5. Hin th theo ni dung di y Who, what and when KING HAS HELP THE POSITION OF PRESIDENT IN DEPT 10 SINCE 17-11-1981 BLAKE HAS HELP THE POSITION OF MANAGER IN DEPT 30 SINCE 01-05-1981 CLARK HAS HELP THE POSITION OF MANAGER IN DEPT 10 SINCE 09-06-1981 JONES HAS HELP THE POSITION OF MANAGER IN DEPT 20 SINCE 02-04-1981 MARTIN HAS HELP THE POSITION OF SALESMAN IN DEPT 30 SINCE 28-09-1981 ALLEN HAS HELP THE POSITION OF SALESMAN IN DEPT 30 SINCE 20-02-1981 TURNER HAS HELP THE POSITION OF SALESMAN IN DEPT 30 SINCE 08-09-1981 JAMES HAS HELP THE POSITION OF CLERK IN DEPT 30 SINCE 03-12-1981 WARD HAS HELP THE POSITION OF SALESMAN IN DEPT 30 SINCE 22-02-1981 FORD HAS HELP THE POSITION OF ANALYST IN DEPT 20 SINCE 03-12-1981 SMITH HAS HELP THE POSITION OF CLERK IN DEPT 20 SINCE 17-12-1980 SCOTT HAS HELP THE POSITION OF ANALYST IN DEPT 20 SINCE 09-12-1982 ADAMS HAS HELP THE POSITION OF CLERK IN DEPT 20 SINCE 12-01-1983 MILLER HAS HELP THE POSITION OF CLERK IN DEPT 10 SINCE 23-01-1982 14 rows selected. 6. Hin th cu trc bng emp;

7. Thay i nhn v nh dng hin th ca ct sal v hiredate trong bng emp;

Trang 16

Oracle c bn - SQL v PL/SQL

Chng 3. TRUY VN D LIU C IU KIN


3.1.CC GII HN TRONG TRUY VN D LIU
Trong phn ln cc trng hp ly d liu t database, ta ch cn ly mt phn d liu ch khng cn ly tt c. hn ch cc d liu tr v khng cn thit, ta c th s dng mnh iu kin trong cu lnh truy vn.

Hnh v 4. Hn ch d liu tr v

3.1.1. Mnh WHERE


C php:
SELECT [DISTINCT ] {*, column [alias],...} FROM table [WHERE condition (s)];

Vi:
column alias table condition tn ct d liu tr v tiu ca ct d liu tr v tn bng truy vn d liu mnh iu kin lc d liu tr v

Mnh WHERE dng t iu kin cho ton b cu lnh truy vn. Trong mnh WHERE c th c cc thnh phn: Tn column Ton t so snh Tn column, hng s hoc danh sch cc gi tr

V d:
SELECT DEPTNO, JOB, ENAME, SAL FROM EMP WHERE SAL BETWEEN 1000 AND 2000 ; Trang 17

Oracle c bn - SQL v PL/SQL

Truy vn d liu vi nhiu iu kin Mnh WHERE cho php ghp c nhiu iu kin thng qua cc ton t logic AND/OR. Ton t AND yu cu d liu phi tho mn c 2 iu kin. Ton t OR cho php d liu tho mn 1 trong 2 iu kin. V d:
SELECT DEPTNO, JOB, ENAME, SAL FROM EMP WHERE SAL BETWEEN 1000 AND 2000 AND JOB = MANAGER; SELECT DEPTNO, JOB, ENAME, SAL FROM EMP WHERE SAL BETWEEN 1000 AND 2000 OR JOB = MANAGER; SELECT DEPTNO, JOB, FROM EMP WHERE SAL > 1500 AND JOB = MANAGER OR JOB =SALESMAN; SELECT DEPTNO, JOB, FROM EMP WHERE SAL > 1500 AND (JOB = MANAGER OR JOB =SALESMAN); EMPNO, ENAME, SAL

EMPNO,

ENAME,

SAL

3.1.2. Cc ton t s dng trong mnh WHERE Ton t so


snh Ton t
= !=, ^=, '+, <\> > < >= <=

Din gii Ton t bng hay tng ng Ton t khc hay khng tng ng Ton t ln hn Ton t nh hn Ton t ln hn hoc bng Ton t nh hn hoc bng

Cc ton t ca SQL Ton t


[NOT] BETWEEN x AND

Din gii
y [Khng] ln hn hoc bng x v nh hn hoc bng y Thuc bt k gi

IN (danh sch): x [NOT] LIKE y

tr no trong danh sch ng nu x [khng] ging khung mu y Cc k t dng trong khun mu: Du gch di (_) : Ch mt k t bt k Du phn trm (%) : Ch mt nhm k t bt k Kim tra gi tr rng Tr v TRUE nu c tn ti

IS [NOT] NULL EXISTS

Trang 18

Oracle c bn - SQL v PL/SQL

Cc ton t logic Ton t


NOT AND OR

Din gii Ph nh mnh Yu cu d liu phi tho mn c 2 iu kin Cho php d liu tho mn 1 trong 2 iu kin

Cp u tin khi thc hin i vi cc loi ton t Cp u tin


1 2 3 4

Ton t Cc ton t so snh


NOT AND OR

3.1.3. V d s dng cc ton t iu kin


[NOT] BETWEEN x AND y V d chn nhn vin c lng nm trong khong 2000 v 3000
SELECT * FROM emp WHERE sal BETEEN 2000 AND 3000;

IN (danh sch) Chn nhn vin c lng bng mt trong 2 gi tr 1400 hoc 3000
SELECT * FROM emp WHERE sal IN (1400, 3000);

Tm tn phng ban nu phng c nhn vin lm vic.


SELECT dname FROM dept WHERE EXISTS (SELECT * FROM emp WHERE dept.deptno = emp.deptno);

x [NOT] LIKE y Tm nhn vin c tn bt u bng chui SMITH


SELECT * FROM emp WHERE ename LIKE 'SMITH_';

chn nhng nhn vin c tn bt u bng 'SM'


SELECT * FROM emp WHERE ename LIKE 'SM%';

tm nhng nhn vin c tn c chui 'A_B'


SELECT ename FROM emp WHERE ename LIKE '%A\_B%'; ESCAPE '\'

V k hiu "_" dng i din cho mt k t bt k nn nu khng c mnh ESCAPE, cu lnh trn s tm tt c cc nhn vin tn AAB, ABB, ACB, v.v... Nu mun k hiu "_" mang ngha nguyn thy, tc l khng cn i din cho k t bt k na, ta t du "\" trc k hiu. ng thi khai bo thm mnh ESCAPE "\"
Trang 19

Oracle c bn - SQL v PL/SQL

Ta cng c th dng mt k t bt k thay cho "\". Chng hn mnh sau c cng kt qu vi mnh trn
SELECT ename FROM emp WHERE ename LIKE '%A^_B%'; ESCAPE '^';

Ta gi cc k t nh "\" hay "^" ni trn l cc k t ESCAPE.

IS [NOT] NULL V d:
SELECT * FROM emp WHERE comm IS NULL ;

3.2.SP XP D LIU TR V
3.2.1. Mnh ORDER BY
C php:
SELECT [DISTINCT ] {*, column [alias],...} FROM table; [WHERE condition] [ORDER BY expr/position [DESC/ASC]];

Mnh ORDER BY dng sp xp s liu c hin th v phi t v tr sau cng ca cu lnh truy vn. V d:
SELECT ENAME, JOB, FROM EMP ORDER BY ENAME; SAL*12, DEPTNO

Mnh ORDER BY mc nh sp xp theo th t tng dn ASC[ENDING] S thp trc Ngy nh trc K t theo bng ch ci sp xp theo th t ngc li (gim dn) t t kho DESC[ENDING] sau column cn sp th t. Vi d:
SELECT ENAME, JOB, HIREDATE FROM EMP ORDER BY HIREDATE DESC ;

3.2.2. Sp xp nhiu ct d liu tr v


Mnh Order cn c th sp xp nhiu column. Cc column cn sp xp c vit th t sau mnh ORDER BY v cch bi du phy (,). Column no gn mnh ORDER BY hn c mc u tin khi sp xp cao hn. Ch nh cch thc sp xp ASC/DESC c vit sau column cch bi mt du cch. V d:
SELECT DEPTNO, JOB, ENAME, SAL

Trang 20

Oracle c bn - SQL v PL/SQL FROM EMP ORDER BY DEPTNO, SAL DESC ;

Order gi tr NULL Ring i vi gi tr NULL, nu sp xp theo th t ASCENDING s nm cc v tr cui cng. Ch : C th ch nh sp xp theo th t cc column trong mnh SELECT. V d:
SELECT DEPTNO, JOB, ENAME, SAL FROM EMP ORDER BY 2;

3.3.BI TP
1. Chn nhn vin trong bng EMP c mc lng t 1000 n 2000 (chn cc trng ENAME, DEPTNO, SAL).
ENAME ALLEN WARD MARTIN TURNER ADAMS MILLER DEPTNO 30 30 30 30 20 10 SAL 1600 1250 1250 1500 1100 1300

2. Hin th m phng ban, tn phng ban, sp xp theo th t tn phng ban.


DEPTNO DNAME 10 40 20 30 ACCOUNTING OPERATIONS RESEARCH SALES

3. Hin th danh sch nhng nhn vin lm ti phng 10 v 20 theo th t A,B,C


EMPNO ENAME JOB 7876 7782 7902 7566 7839 7934 7788 7369 ADAMS CLERK CLARK MANAGER FORD ANALYST JONES MANAGER KING PRESIDENT MILLER CLERK SCOTT ANALYST SMITH CLERK MGR HIREDATE 7788 7839 7566 7839 12-01-1983 09-06-1981 03-12-1981 02-04-1981 17-11-1981 7782 23-01-1982 7566 09-12-1982 7902 17-12-1980 SAL COMM DEPTNO 1100 2450 3000 2975 5000 1300 3000 800 20 10 20 20 10 10 20 20

4. Hin th tn v ngh nghip nhng nhn vin lm ngh th k (cleck) ti phng 20.
ENAME SMITH ADAMS JOB CLERK CLERK

Trang 21

Oracle c bn - SQL v PL/SQL

5. Hin th tt c nhng nhn vin m tn c cc k t TH v LL.


ENAME SMITH ALLEN MILLER

6. Hin th tn nhn vin, ngh nghip, lng ca nhng nhn vin c gim c qun l.
ENAME SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT TURNER ADAMS JAMES FORD MILLER JOB CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST SALESMAN CLERK CLERK ANALYST CLERK SAL 800 1600 1250 2975 1250 2850 2450 3000 1500 1100 950 3000 1300

13 rows selected.

7. Hin th tn nhn vin, m phng ban, ngy gia nhp cng ty sao cho gia nhp cng ty trong nm 1983.
ENAME ADAMS DEPTNO HIREDATE 20 12-JAN-83

8. Hin th tn nhn vin, lng mt nm (ANUAL_SAL ), thng sao cho lng ln hn thng v ngh nghip l SALEMAN, sp theo th t lng gim dn v tn tng dn.
ANUAL_SAL 19200 18000 15000 COMM 300 0 500

Trang 22

Oracle c bn - SQL v PL/SQL

Chng 4. CC HM SQL
4.1.TNG QUAN V HM SQL
4.1.1. Cu trc hm SQL
Hm SQL l mt c im lm tng kh nng s dng cu lnh SQL. Hm SQL c th nhn nhiu tham s vo v tr v ch mt gi tr.

Hnh v 5. Cu trc hm SQL

Hm

SQL

mt

im

sau:

Thc hin vic tnh ton ngay trn d liu C th thao tc, thay i ngay trn tng mc d liu tr v Hoc cng c th thao tc trn nhm cc d liu tr v C th nh dng li cc d liu tr v c kiu s, hay kiu thi gian C th chuyn i kiu d liu tr v

4.1.2. Phn loi hm SQL


Hm SQL c th phn ra lm hai loi: Hm tc ng trn tng dng d liu: Gi tr tr v tng ng vi tng d liu u vo ti mi dng d liu. Hm tc ng trn nhm cc dng d liu: Gi tr tr v tng ng vi cc php thao tc trn nhm d liu tr v.

Trang 23

Oracle c bn - SQL v PL/SQL

Hnh v 6. Phn loi hm SQL

4.2.HM SQL THAO TC TRN TNG DNG D LIU


4.2.1. Cc hm thao tc trn kiu d liu s
u vo v u ra l cc gi tr kiu s

Mt s hm SQL hay dng Hm SQL


ROUND(n[,m]) TRUNC(n[,m]) CEIL(n) FLOOR(n) POWER(m,n) EXP(n) SQRT(n) SIGN(n)

Din gii Cho gi tr lm trn ca n (n cp m, mc nhin m=0) Cho gi tr n ly m ch s tnh t chm thp phn Cho s nguyn nh nht ln hn hoc bng n Cho s nguyn ln nht bng hoc nh hn n Cho ly tha bc n ca m Cho gi tr ca en Cho cn bc 2 ca n, n>=0 Cho du ca n.
n<0 c SIGN(n)= -1 n=0 c SIGN(n)= 0 n>0 c SIGN(n)= 1

ABS(n) MOD(m,n)

Cho gi tr tuyt i Cho phn d ca php chia m cho n

Mt s hm kiu s tham kho khc Hm SQL


LOG(m,n) SIN(n)

Din gii Cho logarit c s m ca n Tr v cosin ca n (n tnh bng radian)

Trang 24

Oracle c bn - SQL v PL/SQL COS(n) TAN(n)

Cho cosin ca n (n tnh bng radian) Tr v cotang ca n (n tnh bng radian)

V d hm ROUND(n[,m])
SELECT ROUND(4.923,1), ROUND(4.923), ROUND(4.923,-1), ROUND(4.923,2) FROM DUMMY; ROUND(4.923,1) ROUND(4.923) ROUND(4.923,-1) ROUND(4.923,2) 4.9 5 0 4.92

V d hm TRUNC(n[,m])
SELECT TRUNC (4.923,1), TRUNC (4.923), TRUNC (4.923,-1), TRUNC (4.923,2) FROM DUMMY; TRUNC(4.923,1) TRUNC(4.923) TRUNC(4.923,-1) TRUNC(4.923,2) 4.9 4 0 4.92

V d hm CEIL(n)
SELECT CEIL (SAL), CEIL(99.9),CEIL(101.76), CEIL(-11.1) FROM EMP WHERE SAL BETWEEN 3000 AND 5000; CEIL(SAL) CEIL(99.9) CEIL(101.76) CEIL(-11.1) 5000 3000 3000 100 100 100 102 102 102 -11 -11 -11

V d hm FLOOR(n)
SELECT FLOOR (SAL), FLOOR (99.9), FLOOR (101.76), FLOOR (-11.1) FROM EMP WHERE SAL BETWEEN 3000 AND 5000; FLOOR(SAL) FLOOR(99.9) FLOOR(101.76) FLOOR(-11.1) 5000 3000 3000 99 99 99 101 101 101 -12 -12 -12

V d hm POWER(m,n)
SELECT SAL, POWER(SAL,2), FROM EMP WHERE DEPTNO =10; POWER(SAL,3), POWER(50,5)

SAL POWER(SAL,2) POWER(SAL,3) POWER(50,5)

Trang 25

Oracle c bn - SQL v PL/SQL

5000 2450 1300

25000000 6002500 1690000

1.2500E+11 1.4706E+10 2197000000

312500000 312500000 312500000

V d hm EXP(n)
SELECT EXP(4) FROM DUMMY; EXP(4) 54.59815

V d hm SQRT(n)
SELECT SAL, SQRT(SAL), FROM EMP WHERE DEPTNO =10; SQRT(40), SQRT (COMM)

SAL SQRT(SAL) SQRT(40) SQRT(COMM) 5000 70.7106781 6.32455532 2450 49.4974747 6.32455532 1300 36.0555128 6.32455532

V d hm SIGN(n)
SELECT SAL-NVL(COMM,0), SIGN(SAL-NVL(COMM,0)), NVL(COMM,0)-SAL, SIGN(NVL(COMM,0)-SAL) FROM EMP WHERE DEPTNO =30 SAL-NVL(COMM,0)SIGN(SAL-NVL(COMM,0))NVL(COMM,0)-SAL SIGN(NVL(COMM,0) SAL) 2850 -150 1300 1500 950 750 1 -1 1 1 1 1 -2850 150 -1300 -1500 -950 -750 -1 1 -1 -1 -1 -1

4.2.2. Cc hm thao tc trn kiu d liu k t


Hm SQL thao tc trn kiu d liu l k t Hm SQL
CONCAT(char1, char2) INITCAP(char) LOWER(char) LPAD(char1, n [,char2])

Din gii Cho kt hp ca 2 chui k t, tng t nh s dng ton t || Cho chui vi k t u cc t l k t hoa Cho chui k t vit thng (khng vit hoa) Cho chui k t c chiu di bng n. Nu chui char1 ngn hn n th thm vo bn tri chui char2 cho n k t. Nu chui char1 di hn n th gi li n
Trang 26

Oracle c bn - SQL v PL/SQL

k t tnh t tri sang


LTRIM(char1, n [,char2]) NLS_INITCAP(char) REPLACE(char,search_string[,replacem ent_string]) RPAD(char1, n [,char2]) RTRIM(char1, n [,char2]) SOUNDEX(char) SUBSTR(char, m [,n])

B cc k t trng bn tri Cho chui vi k t u cc t l ch hoa, cc ch cn li l ch thng Thay tt c cc chui search_string c trong chui char bng chui replacement_string. Ging LPAD(char1, n [,char2]) nhng cn phi. B cc k t trng bn phi Cho chui ng m ca char. Cho chui con ca chui char ly t v tr m v phi n k t, nu khng ch n th ly cho n cui chui Cho chui trong mi k t trong chui from thay bng k t tng ng trong chui to, nhng k t trong chui from khng c tng ng trong chui to s b loi b. Cho chui ch hoa ca chui char Cho k t ASCII ca byte u tin ca chui char Tm v tr chui char2 trong chui char1 bt u t v tr n, ln xut hin th m. Cho chiu di ca chui char

TRANSLATE(char, from, to)

UPPER(char) ASCII(char) INSTR(char1, char2 [,n[,m]])

LENGTH(char)

V d hm LOWER(char)
SELECT LOWER(DNAME), LOWER(SQL COURSE) FROM DEPT;

LOWER(DNAME) LOWER('SQL accounting research sales operations sql sql sql sql course course course course

V d hm UPPER(char)
SELECT ENAME FROM EMP WHERE ENAME = UPPER(Smith); ENAME SMITH

V d hm INITCAP(char)
SELECT INITCAP(DNAME), INITCAP(LOC) FROM DEPT;

INITCAP(DNAME) INITCAP(LOC) Trang 27

Oracle c bn - SQL v PL/SQL

Accounting Research Sales Operations

New York Dallas Chicago Boston

V d hm CONCAT(char1, char2)
SELECT CONCAT(ENAME, JOB) JOB FROM EMP WHERE EMPNO = 7900; JOB JAMES CLERK

V d hm LPAD(char1, n [,char2])
SELECT LPAD(DNAME,20,*), LPAD(DNAME,20), LPAD(DEptno,20, ) FROM DEPT; LPAD(DNAME,20,'*') LPAD(DNAME,20) ***ACCOUNTING ***RESEARCH ***SALES ***OPERATIONS ACCOUNTING RESEARCH SALES OPERATIONS LPAD(DEPTNO,20,'') 10 20 30 40

V d hm RPAD(char1, n [,char2])
SELECT RPAD(DNAME,20,*), RPAD(DNAME,20), RPAD(DEptno,20, ) FROM DEPT; RPAD(DNAME,20,'*') RPAD(DNAME,20) ACCOUNTING RESEARCH SALES OPERATIONS *** *** *** *** ACCOUNTING RESEARCH SALES OPERATIONS RPAD(DEPTNO,20,'') 10 20 30 40

V d hm SUBSTR(char, m [,n])
SELECT SUBSTR(ORACLE,2,4), FROM DEPT; SUBS SUBSTR(DNAME, SUBST RACL RACL RACL RACL CCOUNTING ESEARCH ALES PERATIONS COUNT SEARC LES ERATI SUBSTR(DNAME,2), SUBSTR(DNAME,3,5)

V d hm INSTR(char1, char2 [,n[,m]])


SELECT DNAME, INSTR(DNAME, A), INSTR(DNAME,ES), INSTR(DNAME,C,1,2) FROM DEPT; DNAME ACCOUNTING INSTR(DNAME,'A') INSTR(DNAME,'ES') INSTR(DNAME,'C',1,2) 1 0 3 Trang 28

Oracle c bn - SQL v PL/SQL RESEARCH SALES OPERATIONS 5 2 5 2 4 0 0 0 0

V d hm LTRIM(char1, n [,char2])
SELECT DNAME, LTRIM(DNAME,A), LTRIM(DNAME,AS), LTRIM(DNAME,ASOP) FROM DEPT; DNAME ACCOUNTING RESEARCH SALES OPERATIONS LTRIM(DNAME,'A LTRIM(DNAME,'A LTRIM(DNAME,'A CCOUNTING RESEARCH SALES OPERATIONS CCOUNTING RESEARCH LES OPERATIONS CCOUNTING RESEARCH LES ERATIONS

V d hm RTRIM(char1, n [,char2])
SELECT DNAME, RTRIM(DNAME,A), RTRIM(DNAME,AS), RTRIM(DNAME,ASOP) FROM DEPT; DNAME ACCOUNTING RESEARCH SALES OPERATIONS RTRIM(DNAME,'A RTRIM(DNAME,'A RTRIM(DNAME,'A ACCOUNTING RESEARCH SALES OPERATIONS ACCOUNTING RESEARCH SALES OPERATIONS ACCOUNTING RESEARCH SALES OPERATIONS

V d hm SOUNDEX(char)
SELECT ENAME, SOUNDEX(ENAME) FROM EMP WHERE SOUNDEX(ENAME)= SOUNDEX(FRED); ENAME FORD SOUN F630

V d hm LENGTH(char)
SELECT LENGTH(SQL FROM DEPT; COURSE), LENGTH(DEPTNO), LENGTH(DNAME)

LENGTH('SQLCOURSE') LENGTH(DEPTNO) LENGTH(DNAME) 10 10 10 10 2 2 2 2 14 14 14 14

V d hm TRANSLATE(char, from, to)


SELECT ENAME, TRANSLATE(ENAME,'C','F'), TRANSLATE(JOB,'AR','IT') FROM EMP WHERE DEPTNO = 10; ENAME TRANSLATE( JOB TRANSLATE Trang 29 JOB,

Oracle c bn - SQL v PL/SQL

KING CLARK MILLER

KING FLARK MILLER

PRESIDENT PTESIDENT MANAGER MINIGET CLERK CLETK

V d hm REPLACE(char,search_string[,replacement_string])
SELECT JOB, REPLACE(JOB, SALESMAN, SALESPERSON), ENAME, REPLACE(ENAME, CO,PR)

FROM EMP WHERE DEPTNO =30 OR DEPTNO =20; JOB REPLACE(JOB,'SALESMAN', ENAME BLAKE JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS REPLACE(ENAME,'CO',' BLAKE JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SPRTT ADAMS

MANAGER MANAGER MANAGER MANAGER SALESMAN SALESPERSON SALESMAN SALESPERSON SALESMAN SALESPERSON CLERK CLERK SALESMAN SALESPERSON ANALYST ANALYST CLERK CLERK ANALYST ANALYST CLERK CLERK

V d cc hm lng nhau:
SELECT DNAME, LENGHT(DNAME), LENGHT(TRANSLATE,DNAME, AS,A)) FROM DEPT; DNAME ACCOUNTING RESEARCH SALES OPERATIONS LENGTH(DNAME) LENGTH(TRANSLATE(DNAME,'AS','A')) 14 14 14 14 14 13 12 13

4.2.3. Cc hm thao tc trn kiu d liu thi gian Hm SQL


thao tc trn kiu d liu l thi gian. Hm SQL
MONTH_BETWEEN(d1, ADD_MONTHS(d,n) NEXT_DAY(d, char ) LAST_DAY(d) d2)

Din gii Cho bit s thng gia ngy d1 v d2. Cho ngy d thm n thng. Cho ngy tip theo ngy d c th ch bi char. Cho ngy cui cng trong thng ch bi d.

V d hm MONTH_BETWEEN(d1, d2)
SELECT MONTHS_BETWEEN( SYSDATE, HIREDATE), MONTHS_BETWEEN('01-01-2000','05-10-2000') FROM EMP WHERE MONTHS_BETWEEN( SYSDATE,HIREDATE)>240; MONTHS_BETWEEN(SYSDATE,HIREDATE) TWEEN('01-01-2000','05-10-2000')

Trang 30

Oracle c bn - SQL v PL/SQL 241.271055 241.206539 243.367829 -9.1290323 -9.1290323 -9.1290323

V d hm ADD_MONTHS(d,n)
SELECT HIREDATE, FROM EMP WHERE DEPTNO=20; ADD_MONTHS(HIRE,3), ADD_MONTHS(HIREDATE,-3)

HIREDATE ADD_MONTHS ADD_MONTHS 02-04-1981 02-07-1981 02-01-1981 03-12-1981 03-03-1982 03-09-1981 17-12-1980 17-03-1981 17-09-1980 09-12-1982 09-03-1983 09-09-1982 12-01-1983 12-04-1983 12-10-1982

V d hm NEXT_DAY(d, char )
SELECT HIREDATE, FROM EMP WHERE DEPTNO = 10; NEXT_DAY(HIREDATE,FRIDAY), NEXT_DAY(HIREDATE,6)

HIREDATE NEXT_DAY(H NEXT_DAY(H 17-11-1981 20-11-1981 20-11-1981 09-06-1981 12-06-1981 12-06-1981 23-01-1982 29-01-1982 29-01-1982

V d hm LAST_DAY(d)
SELECT SYSDATE, LAST_DAY(SYSDATE), LAST_DAY(15-01-2001) FROM EMP WHERE DEPTNO =20; SYSDATE HIREDATE, LAST_DAY(HIREDATE),

LAST_DAY(S HIREDATE LAST_DAY(H LAST_DAY('

28-03-2001 31-03-2001 02-04-1981 30-04-1981 31-01-2001 2803-2001 31-03-2001 03-12-1981 31-12-1981 31-01-2001 28-032001 31-03-2001 17-12-1980 31-12-1980 31-01-2001 28-032001 31-03-2001 09-12-1982 31-12-1982 31-01-2001 28-032001 31-03-2001 12-01-1983 31-01-1983 31-01-2001

Mt s hm khc c th p dng cho kiu ngy Hm SQL


ROUND(date1) ROUND(date1,MONTH)

Din gii Tr v ngy date 1 ti thi im gia tra 12:00 AM Nu date 1 nm trong na thng u tr v ngy u tin ca thng, ngc li s tr v ngy u tin ca thng sau. Nu date 1 nm trong na nm u tr v ngy u tin ca thng, ngc li s tr v ngy u tin ca nm sau. Tr v ngy u tin ca thng cha date1 Tr v ngy u tin ca nm cha date1

ROUND(date1,YEAR)

TRUNC(date1,

MONTH)

TRUNC(date1, YEAR)

Trang 31

Oracle c bn - SQL v PL/SQL

4.2.4. Cc hm chuyn i kiu


Hm SQL
TO_CHAR(number|date, fmt) TO_NUMBER(char) TO_DATE(chsr,fmt)

Din gii Chuyn kiu s v ngy v kiu k t. Chuyn k t c ni dung s sang s Chuyn k t sang kiu ngy vi nh dng t trong fmt. So snh biu thc expr vi gi tr search nu ng tr v gi tr result nu khng tr v gi tr default. Chuyn gi tr COL|VALUE thnh val nu null. Tr gi tr ln nht trong dy gi tr.

DECODE(EXPR, SEARCH1, RESULT1, SEARCH2, RESULT2, DEFAULT): NVL(COL|VALUE, VAL) Greatest(col|value1, col|value2)

V d:
SELECT To_char (sysdate, day, ddth month yyyy) from dummy; SELECT EMPNO, ENAME, HIREDATE FROM EMP WHERE HIREDATE = TO_DATE (June 4, 1984, month dd, yyyy); INSERT INTO EMP (EMPNO, DEPTNO, HIREDATE VALUES (777, 20, TO_DATE(19-08-2000, DD-MM-YYYY); SELECT ENAME, JOB, DECODE (JOB, CLERK,WWORKER,MANAGER,BOSS,UNDEFINED) DECODED_JOB FROM EMP; SELECT GREATEST(1000,2000), WHERE DEPTNO = 10; GREATEST(SAL,COMM) FROM EMP

Cc khun dng ngy Hm SQL


SCC hoc CC YYYY hoc SYYYY YYY, YY, Y IYYY, IYY, IY, I SYEAR, YEAR Q MM MONTH MON WW, W DDD, DD, D DAY DY

Din gii Th k; S ch ngy BC Nm; S ch ngy BC Ch nm vi 3,2,1 k t s Ch nm theo chun ISO Ch nm theo cch pht m ca ngi anh; Qu trong nm Gi tr thng vi 2 s (01-12) Tn y ca thng theo ting anh, di 9 Thng vi 3 k t vin tt (JAN, FEB...) Tun trong nm hoc trong thng Ngy trong nm, thng hoc tun Ch th trong tun Ch th trong tun vi 3 k t vit tt
Trang 32

Oracle c bn - SQL v PL/SQL

J AM, PM HH, HH12 HH24 MI SS SSSSS / . , char TH SP SPTH, THSP RR

Ngy Julian; bt u t ngy 31/12/4713 trc cng nguyn Ch nh sng, chiu Ch gi trong ngy (1-12) hoc (0-23) Pht (0-59) Giy (0-59) S giy n na m (0-86399) c t ng thm khi t trong khun dng on k t t trong nhy p c t ng thm khi t trong khun dng Thm phn th t (1st, 2nd, 4th ) Pht m s ( FOUR vi DDSP) Pht m v chuyn sang dng th t ( First, second, ...) Ngy chuyn giao thin nin k vi cc nm <1999.

Nm Nm hin t
0-49 50-99

0-49 th k hin ti Th k trc

50-99 Th k sau Th k hin ti

Mt

khun

dng

s Din gii V d
999999 099999 $999999 L999999 999999.99 999,999 999999MI 999999PR 99.9999RRRR 9999V99 B9999.99

K t
9 0

Kt qu
1234 001234 $1234 FF1234 1234.00 1,234 1234<1234> 1.234E+03 123400 1234.00

Xc nh hin th 1 s Hin th c s 0 u nu di khun dng ln hn s hin c $Thm k t tin t

Thm k t tin t bn a Du thp phn

, MI PR

Du phn cch phn nghn Du m bn phi ( vi cc gi tr m) Thm ngoc nhn vo cc gi tr m

EEE Chuyn sang hin th s E V B

Nhn vi 10 n, n l s cc s 9 t sau V Hin th c gi tr 0 nu = 0.

Trang 33

Oracle c bn - SQL v PL/SQL

4.3.HM THAO TC TRN TP HP


4.3.1. Cc hm tc ng trn nhm
Cc hm tc ng trn nhm cc dng d liu hay tc ng ln mt tp hp cc cc dng d liu bao gm: Hm SQL
AVG([DISTINCT/ALL] n) COUNT([DISTINCT/ALL] expr) MAX([DISTINCT/ALL] expr) MIN([DISTINCT/ALL] expr) STDDVE([DISTINCT/ALL] n) SUM([DISTINCT/ALL] n) VARIANCE([DISTINCT/ALL] n)

Din gii Gi tr trung bnh ca n,khng k tr null S row c expr khc null Gi tr ln nht ca expr Gi tr nh nht ca expr Phng sai ca n khng k tr null Tng ca ca n khng k tr null Variance ca n khng k tr null

Ch : Tt c cc hm trn nhm mu tin u b qua gi tr NULL tr hm COUNT. Dng hm NVL chuyn i v tnh gi tr NULL. C 2 cch dng cc cc hm ny Tc ng trn ton b cc dng d liu ca cu lnh truy vn Tc ng trn mt nhm d liu cng tnh cht ca cu lnh truy vn. Cng tnh cht c ch bi mnh :
[GROUP BY expr] [HAVING condition]

V d: Tc ng trn ton b cc dng d liu ca cu lnh truy vn: Tnh mc lng trung bnh ca ton b nhn vin
Select AVG(SAL) FROM EMP;

Tnh mc lng thp nht ca nhn vin lm ngh CLERK


Select MIN(SAL) FROM EMP WHERE JOB =CLERK:

V d: Tc ng trn mt nhm d liu cng tnh cht ca cu lnh truy vn. Tnh mc lng trung bnh ca tng loi ngh nghip
SELECT JOB, AVG(SAL) FROM EMP GROUP BY JOB;

Ch : Ch c cng t trong mnh SELECT cc hm nhm hoc cc column t trong mnh GROUP BY. V d:
ng: SELECT MAX(SAL), JOB FROM EMP GROUP BY JOB;

Trang 34

Oracle c bn - SQL v PL/SQL Sai: SELECT MAX(SAL), JOB FROM EMP;

4.3.2. Mnh GROUP BY


C php:
SELECT [DISTINCT ] {*, column [alias],...} FROM table; [WHERE condition] [GROUP BY expr] [HAVING condition] [ORDER BY expr/position [DESC/ASC]]

Mnh GROUP BY s nhm cc dng d liu c cng gi tr ca expr. V d:


GROUP BY JOB ngha l s nhm cc ngh ging nhau.

Mnh HAVING l t iu kin ca nhm d liu. Mnh ny khc mnh WHERE ch mnh WHERE t iu kin cho ton b cu lnh SELECT. V d:
SELECT JOB, MAX(SAL) FROM EMP WHERE JOB !=MANAGER GROUP BY JOB; JOB ANALYST CLERK PRESIDENT SALESMAN MAX(SAL) 3000 1300 5000 1600

SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB HAVING COUNT(*)>3; JOB CLERK SALESMAN MAX(SAL) 1300 1600

SELECT JOB, MAX(SAL) FROM EMP HAVING MAX(SAL)>=3000 GROUP BY JOB; JOB ANALYST PRESIDENT MAX(SAL) 3000 5000

Trang 35

Oracle c bn - SQL v PL/SQL

4.4.MT S HM MI B SUNG TRONG Oracle9i


4.4.1. Hm NULLIF
C php: NULLIF(expr1, expr2) Hm tr v gi tr NULL nu biu thc th nht bng biu thc th 2. Trong trng hp ngc li, n tr v gi tr ca biu thc th nht.

4.4.2. Hm COALSCE
C php: COALESCE(expr1, expr2, expr3, ...) Tr v gi tr ca tham s u tin khc null

4.4.3. Cu lnh case


V d: Case cu lnh SELECT ENAME, EXTRACT(YEAR FROM HIREDATE) (CASE EXTRACT(YEAR FROM HIREDATE) WHEN 2002 THEN 'NEW HIRE' WHEN 1997 THEN 'FIVE YEARS SERVICE' WHEN 1992 THEN 'TEN YEARS SERVICE' ELSE 'NO AWARD THIS YEAR' END ) AS AWARD FROM EMP; CASE biu thc SELECT ENAME, SAL, (CASE WHEN JOB = DBA THEN SAL * 1.5 WHEN HIREDATE < SYSDATE - TO_YMINTERVAL(05-00) THEN SAL * 1.25 WHEN DEPTNO IN (40,30,10) THEN SAL * 1.1 ELSE SAL * .9 END ) AS NEW_SAL FROM EMP; AS YEAR_OF_HIRE,

4.5.BI TP
4.5.1. Hm trn tng dng d liu
1. Lit k tn nhn vin, m phng ban v lng nhn vin c tng 15% (PCTSAL).
DEPTNO ENAME 10 30 10 20 KING BLAKE CLARK JONES PCTSAL 5000 2850 2450 2975 Trang 36

Oracle c bn - SQL v PL/SQL 30 30 30 30 30 20 20 20 20 10 MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER 1250 1600 1500 950 1250 3000 800 3000 1100 1300

2. Vit cu lnh hin th nh sau:


EMPLOYEE_AND_JOB KING*** *PRESIDENT BLAKE*** **MANAGER CLARK*** **MANAGER JONES*** **MANAGER MARTIN******SALESMAN ALLEN*** *SALESMAN TURNER******SALESMAN JAMES*** *CLERK WARD*** **SALESMAN FORD*** ***ANALYST SMITH*** *CLERK SCOTT*** **ANALYST ADAMS*** *CLERK MILLER*** ***CLERK

3. Vit cu lnh hin th nh sau:


EMPLOYEE KING (President) BLAKE (Manager) CLARK (Manager) JONES (Manager) MARTIN (Salesman) ALLEN (Salesman) TURNER (Salesman) JAMES (Clerk) WARD (Salesman) FORD (Analyst) SMITH (Clerk) SCOTT (Analyst) ADAMS (Clerk) MILLER (Clerk)

4. Vit cu lnh hin th nh sau:


ENAME BLAKE MARTIN ALLEN TURNER JAMES WARD DEPTNO JOB 30 30 30 30 30 30 Manager Salesperson Salesperson Salesperson Clerk Salesperson

Trang 37

Oracle c bn - SQL v PL/SQL

5. Tm ngy th 6 u tin cch 2 thng so vi ngy hin ti hin th ngy di dng 09 February 1990. 6. Tm thng itn v tn nhn vin, ngy gia nhp cng ty ca nhn vin phng s 20, sao cho hin th nh sau:
ENAME JONES FORD SMITH SCOTT ADAMS DATE_HIRED april,SECOND 1981 december,THIRD 1981 december,SEVENTEENTH 1980 december,NINTH 1982 january,TWELFTH 1983

7. Hin th tn nhn vin, ngy gia nhp cng ty, ngy xt nng lng (sau ngy gia nhp cng ty 1 nm), sp xp theo th t ngy xt nng lng.
ENAME SMITH ALLEN WARD JONES BLAKE CLARK TURNER MARTIN KING JAMES FORD MILLER SCOTT ADAMS HIREDATE REVIEW 17-12-1980 20-02-1981 22-02-1981 02-04-1981 01-05-1981 09-06-1981 08-09-1981 28-09-1981 17-11-1981 03-12-1981 03-12-1981 23-01-1982 09-12-1982 12-01-1983 17-12-1981 20-02-1982 22-02-1982 02-04-1982 01-05-1982 09-06-1982 08-09-1982 28-09-1982 17-11-1982 03-12-1982 03-12-1982 23-01-1983 09-12-1983 12-01-1984

8. Hin th tn nhn vin v lng di dng


ENAME ADAMS ALLEN BLAKE CLARK FORD JAMES JONES KING MARTIN MILLER SCOTT SMITH TURNER WARD SALARY BELOW 1500 1600 2850 2450 3000 BELOW 1500 2975 5000 BELOW 1500 BELOW 1500 3000 BELOW 1500 On Target BELOW 1500

9. Cho bit th ca ngy hin ti 10. a chui di dng nn/nn, kim tra nu khng khun dng tr li l YES, ngc li l NO. Kim tra vi cc chui 12/34, 01/1a, 99\88
VALUE VALID?

Trang 38

Oracle c bn - SQL v PL/SQL 12/34 YES

11. Hin th tn nhn vin, ngy gia nhp cng ty, ngy lnh lng sao cho ngy lnh lng phi vo th 6, nhn vin ch c nhn lng sau t nht 15 ngy lm vic ti cng ty, sp xp theo th t ngy gia nhp cng ty.

4.5.2. Hm trn nhm d liu


1. Tm lng thp nht, ln nht v lng trung bnh ca tt c cc nhn vin

2. Tm lng nh nht v ln ca mi loi ngh nghip

3. Tm xem c bao nhiu gim c trong danh sch nhn vin.

4. Tm tt c cc phng ban m s nhn vin trong phng >3 5. Tm ra mc lng nh nht ca mi nhn vin lm vic cho mt gim c no sp xp theo th t tng dn ca mc lng.

Trang 39

Oracle c bn - SQL v PL/SQL

Chng 5. LNH TRUY VN D LIU M RNG


5.1.KT HP D LIU T NHIU BNG
5.1.1. Mi lin kt tng ng
Mi lin kt tng ng c th hin trong mnh WHERE. lin kt trong mnh WHERE phi ch r tn ca cc column v mnh c t tng ng. V d:
emp.deptno =dept.deptno

Cc column trng tn phi c ch r column nm bng no thng qua tn hoc qua alias. Tn trng ny c th t trong cc mnh khc nh SELECT, ORDER BY.. V d:
SELECT DEPT.DEPTNO, ENAME,JOB, FROM EMP, DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO ORDER BY DEPT.DEPTNO; SELECT A.DEPTNO, A.ENAME, FROM EMP A, DEPT B WHERE A.DEPTNO = B.DEPTNO ORDER BY A.DEPTNO; DNAME

A.JOB,

B.DNAME

5.1.2. Mi lin kt khng tng ng


Mi lin kt tng ng c th hin trong mnh WHERE. lin kt trong mnh WHERE phi ch r tn ca cc column v mnh c t khng tng ng. V d:
WHERE E.SAL BETWEEN S. LOSAL AND S.HISAL

Cc column trng tn phi c ch r column nm bng no thng qua tn hoc qua alias. Tn trng ny c th t trong cc mnh khc nh SELECT, ORDER BY.. V d:
SELECT E.ENAME,E.JOB, S.GRADE FROM EMP E, SALGRADE S WHERE E.SAL BETWEEN S. LOSAL AND S.HISAL;

Ch : iu kin lin kt ng l s cc bng - 1 = s cc iu kin lin kt

5.1.3. Mi lin kt cng


Mi lin kt cng tr v c cc gi tr NULL trong biu thc iu kin. Du (+) v no tnh thm cc gi tr NULL v . Mt cu lnh select ch t c 1 mi lin kt cng, du (+) t bn phi column lin kt

Trang 40

Oracle c bn - SQL v PL/SQL

Trong mnh WHERE ca mi lin kt cng khng c dng ton t IN hoc OR ni cc iu kin lin kt khc. V d:
SELECT FROM WHERE AND ENAME BLAKE MARTIN ALLEN TURNER JAMES WARD E.ENAME, D.DEPTNO, D.DNAME EMP E, DEPT D E.DEPTNO (+)=D.DEPTNO D.DEPTNO IN (30, 40); DEPTNO DNAME 30 30 30 30 30 30 40 SALES SALES SALES SALES SALES SALES OPERATIONS

5.1.4. Lin kt ca bng vi chnh n (t thn)


C th lin kt bng vi chnh n bng cch t alias. V du:
Select e.ename emp_name, e.sal emp_sal, m.ename mgr_name, m.sal mgr_sal from emp e, emp m where e.mgr = m.empno and e.sal <m.sal; EMP_NAME BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD SMITH ADAMS MILLER EMP_SAL MGR_NAME 2850 2450 2975 1250 1600 1500 950 1250 800 1100 1300 KING KING KING BLAKE BLAKE BLAKE BLAKE BLAKE FORD SCOTT CLARK MGR_SAL 5000 5000 5000 2850 2850 2850 2850 2850 3000 3000 2450

5.1.5. Cch biu din kt ni mi trong Oracle 9i Tch -cc


CROSS JOIN (Cartesian Product)
SELECT E.ENAME, D.DNAME FROM EMP E CROSS JOIN DEPT D;

Kt ni t nhin NATURAL JOIN (Equijoin on All Identically Named Columns).


SELECT E.ENAME, D.DNAME FROM EMP E NATURAL JOIN DEPT D;

Mnh USING (Tng t nh Natural Join, nhng cho php ch r tn ct c s dng trong php kt ni).

Trang 41

Oracle c bn - SQL v PL/SQL SELECT E.ENAME, D.DNAME FROM EMP E JOIN DEPT D USING (DEPTNO);

Mnh ON (Ch r tn ct tham gia trong php kt ni) SELECT E.ENAME, D.DNAME FROM EMP E JOIN DEPT D ON (E.DEPTNO = D.DEPTNO);

Kt ni tri LEFT OUTER JOIN SELECT E.ENAME, D.DNAME FROM EMP E LEFT OUTER JOIN DEPT D ON (E.DEPTNO = D.DEPTNO);

Kt ni tri RIGHT OUTER JOIN SELECT E.ENAME, D.DNAME FROM EMP E RIGHT OUTER JOIN DEPT D ON (E.DEPTNO= D.DEPTNO);

Kt ni FULL OUTER JOIN (All records from both tablesIdentical to a union of left outer join and right outer join) SELECT E.ENAME, D.DNAME FROM EMP E FULL OUTER JOIN DEPT D ON (E.DEPTNO = D.DEPTNO);

5.1.6. Cc ton t tp hp
Tn ton t
UNION

Din gii Kt hp kt qu ca nhiu cu hi vi nhau, ch gi li mt i din cho cc mu tin trng nhau. cng c lp li

UNION ALL Kt hp kt qu ca nhiu cu hi vi nhau, cc mu tin trng nhau INTERSET MINUS

Ly phn giao cc kt qu ca nhiu cu hi Ly kt qu c trong cu hi th nht m khng c trong cu hi th hai (cu hi sau ton t MINUS)

V d:
Select job from emp where deptno = 10 Union Select job from emp where deptno = 30; JOB CLERK MANAGER PRESIDENT SALESMAN

Trang 42

Oracle c bn - SQL v PL/SQL

5.2.LNH TRUY VN LNG


5.2.1. Cu lnh SELECT lng nhau.
Trong mnh WHERE Tm nhng nhn vin lm cng ngh vi BLAKE
select ename, job from emp where job = (select job from emp where ename = BLAKE); ENAME BLAKE CLARK JONES JOB MANAGER MANAGER MANAGER

Trong mnh HAVING Tm nhng phng c mc lng trung bnh ln hn phng 30


SELECT DEPTNO, AVG(SAL) FROM EMP HAVING AVG(SAL) > (SELECT AVG(SAL) FROM EMP WHERE DEPTNO =30) GROUP BY DEPTNO; DEPTNO AVG(SAL) 10 2916.66667 20 2175

5.2.2. Ton t SOME/ANY/ALL/NOT IN/EXITS


Tn ton t
NOT IN ANY v SOME ALL EXISTS

Din gii Khng thuc So snh mt gi tr vi mi gi tr trong mt danh sch hay trong kt qu tr v ca cu hi con, phi sau ton t = So snh mt gi tr vi mi gi tr trong danh sch hay trong kt qu tr v ca cu hi con. Tr v TRUE nu c tn ti.

V d:
SELECT * FROM emp WHERE sal = ANY (SELECT sal FROM emp WHERE deptno=30); SELECT * FROM emp WHERE sal >= ALL (select distinct sal From emp Where deptno =30) Order by sal desc; SELECT ENAME, SAL, JOB, DEPTNO FROM EMP WHERE SAL > SOME (SELECT DISTINCT SAL FROM EMP WHERE DEPTNO =30)

Trang 43

Oracle c bn - SQL v PL/SQL ORDER BY SAL DESC;

Tm nhng ngi c nhn vin


SELECT EMPNO, ENAME, JOB, DEPTNO FROM EMP E WHERE EXISTS (SELECT EMPNO FROM EMP WHERE EMP.MGR = E.EMPNO);

5.3.CU TRC HNH CY


5.3.1. Cu trc hnh cy trong 1 table
Trong mt table ca CSDL Oracle c th hin cu trc hnh cy. V d trong bng EMP cu trc th hin cp qun l. Root node: l node cp cao nht Child node: l node con hay khng phi l root node Parent node: l node c node con Leaf node: l node khng c node con

Level (cp) Level l mt ct gi cha cp trong cu trc hnh cy. V d.


SELECT LEVEL, DEPTNO, EMPNO, ENAME, JOB, SAL FROM EMP CONNECT BY PRIOR EMPNO = MGR START WITH MGR is NULL; LEVEL 1 2 3 3 3 3 3 2 3 2 3 4 3 4 DEPTNO 10 30 30 30 30 30 30 10 10 20 20 20 20 20 EMPNO ENAME 7839 7698 7654 7499 7844 7900 7521 7782 7934 7566 7902 7369 7788 7876 KING BLAKE MARTIN ALLEN TURNER JAMES WARD CLARK MILLER JONES FORD SMITH SCOTT ADAMS JOB PRESIDENT MANAGER SALESMAN SALESMAN SALESMAN CLERK SALESMAN MANAGER CLERK MANAGER ANALYST CLERK SALEMAN CLERK SAL 5000 2850 1250 1600 1500 950 1250 2450 1300 2975 3000 800 3300 1100

5.3.2. K thut thc hin


C th nh ngha quan h tha k trong cu hi bng mnh STAR WITH v CONNECT BY trong cu lnh SELECT, mi mu tin l mt node trong cy phn cp. Ct gi LEVEL cho bit cp ca mu tin hay cp ca node trong quan h tha k. C php:
SELECT [DISTINCT/ALL] [expr [c_ias]] FROM [table/view/snapshot] [t_alias] [WHERE condition] [START WITH condition CONNECT BY PRIOR condition] [GROUP BY expr] [HAVING condition] [UNION/UNION ALL/INTERSET/MINUS select command] Trang 44

Oracle c bn - SQL v PL/SQL [ORDER BY expr/position [DESC/ASC]]

Vi:
START WITH CONNECT BY PRIOR c t im u ca hnh cy. Khng th column gi level mnh ny. Ch column trong mi lin h tnh cy. nh hng cu trc. Nu prior xut hin trc mgr, Mgr s c tm trc sau n empno, y l hnh cy hng ln. Nu prior xut hin trc empno, empno s c tm trc sau n empno, y l hnh cy hng xung.

V d:
SELECT LEVEL, DEPTNO, EMPNO, ENAME, JOB, SAL FROM EMP CONNECT BY PRIOR MGR = EMPNO START WITH empno = 7876; LEVEL 1 2 3 4 DEPTNO 20 20 20 10 EMPNO ENAME 7876 7788 7566 7839 ADAMS SCOTT JONES KING JOB CLERK SALEMAN MANAGER PRESIDENT SAL 1100 3300 2975 5000

5.3.3. Mnh WHERE trong cu trc hnh cy


Mnh WHERE v CONNECT BY c th c dng ng thi trong cu trc hnh cy. Nu mnh WHERE loi tr mt s row ca cu trc hnh cy th ch nhng row c loi tr. Nu iu kin t trong mnh CONNECT BY th ton b nhnh ca row b loi tr. V d 1:
SELECT LEVEL, DEPTNO, EMPNO, ENAME, JOB, SAL FROM EMP WHERE ENAME != SCOTT CONNECT BY PRIOR EMPNO = MGR START WITH MGR IS NULL; LEVEL 1 2 3 3 3 3 3 2 3 2 3 4 4 DEPTNO 10 30 30 30 30 30 30 10 10 20 20 20 20 EMPNO ENAME 7839 7698 7654 7499 7844 7900 7521 7782 7934 7566 7902 7369 7876 KING BLAKE MARTIN ALLEN TURNER JAMES WARD CLARK MILLER JONES FORD SMITH ADAMS JOB PRESIDENT MANAGER SALESMAN SALESMAN SALESMAN CLERK SALESMAN MANAGER CLERK MANAGER ANALYST CLERK CLERK SAL 5000 2850 1250 1600 1500 950 1250 2450 1300 2975 3000 800 1100

V d 2:
SELECT LEVEL, DEPTNO, EMPNO, ENAME, JOB, SAL FROM EMP CONNECT BY PRIOR EMPNO = MGR AND ENAME != SCOTT

Trang 45

Oracle c bn - SQL v PL/SQL START WITH MGR IS NULL; LEVEL 1 2 3 3 3 3 3 2 3 2 3 4 DEPTNO 10 30 30 30 30 30 30 10 10 20 20 20 EMPNO ENAME 7839 7698 7654 7499 7844 7900 7521 7782 7934 7566 7902 7369 KING BLAKE MARTIN ALLEN TURNER JAMES WARD CLARK MILLER JONES FORD SMITH JOB PRESIDENT MANAGER SALESMAN SALESMAN SALESMAN CLERK SALESMAN MANAGER CLERK MANAGER ANALYST CLERK SAL 5000 2850 1250 1600 1500 950 1250 2450 1300 2975 3000 800

5.4.BI TP
1. Hin th ton b tn nhn vin v tn phng ban lm vic sp xp theo tn phng ban.

2. Hin th tn nhn vin, v tr a l, tn phng vi iu kin lng >1500.


ENAME KING BLAKE CLARK JONES ALLEN FORD SCOTT LOC NEW YORK CHICAGO NEW YORK DALLAS CHICAGO DALLAS DALLAS DNAME ACCOUNTING SALES ACCOUNTING RESEARCH SALES RESEARCH RESEARCH

3. Hin th tn nhn vin, ngh nghip, lng v mc lng.


ENAME JAMES SMITH ADAMS MARTIN WARD MILLER ALLEN TURNER BLAKE CLARK JONES FORD SCOTT KING JOB CLERK CLERK CLERK SALESMAN SALESMAN CLERK SALESMAN SALESMAN MANAGER MANAGER MANAGER ANALYST ANALYST PRESIDENT SAL 950 800 1100 1250 1250 1300 1600 1500 2850 2450 2975 3000 3000 5000 GRADE 1 1 1 2 2 2 3 3 4 4 4 4 4 5

4. Hin th tn nhn vin, ngh nghip, lng v mc lng, vi lng=3.


ENAME ALLEN TURNER JOB SALESMAN SALESMAN SAL 1600 1500 GRADE 3 3

iu kin mc

Trang 46

Oracle c bn - SQL v PL/SQL

5. Hin th nhng nhn vin ti DALLAS


ENAME JONES FORD SMITH SCOTT ADAMS LOC DALLAS DALLAS DALLAS DALLAS DALLAS SAL 2975 3000 800 3000 1100

6. Hin th tn nhn vin , ngh nghip, lng, mc lng, tn phng lm vic tr nhn vin c ngh l cleck v sp xp theo chiu gim.
ENAME MARTIN WARD ALLEN TURNER BLAKE CLARK JONES FORD SCOTT KING JOB SALESMAN SALESMAN SALESMAN SALESMAN MANAGER MANAGER MANAGER ANALYST ANALYST PRESIDENT SAL 1250 1250 1600 1500 2850 2450 2975 3000 3000 5000 GRADE DNAME 2 2 3 3 4 4 4 4 4 5 SALES SALES SALES SALES SALES ACCOUNTING RESEARCH RESEARCH RESEARCH ACCOUNTING

7. Hin th chi tit v nhng nhn vin kim c 36000 $ 1 nm hoc ngh l cleck. (gm cc trng tn, ngh, thu nhp, m phng, tn phng, mc lng)
ENAME JAMES SMITH ADAMS MILLER FORD SCOTT JOB CLERK CLERK CLERK CLERK ANALYST ANALYST ANUAL_SAL DNAME 11400 9600 13200 15600 36000 36000 SALES RESEARCH RESEARCH ACCOUNTING RESEARCH RESEARCH GRADE 1 1 1 2 4 4

8. Hin th nhng phng khng c nhn vin no lm vic.


DEPTNO DNAME 40 OPERATIONS LOC BOSTON

9. Hin th m nhn vin, tn nhn vin, m ngi qun l, tn ngi qun l


EMP_NAME BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER EMP_SAL MGR_NAME 2850 2450 2975 1250 1600 1500 950 1250 3000 800 3000 1100 1300 KING KING KING BLAKE BLAKE BLAKE BLAKE BLAKE JONES FORD JONES SCOTT CLARK MGR_SAL 5000 5000 5000 2850 2850 2850 2850 2850 2975 3000 2975 3000 2450

Trang 47

Oracle c bn - SQL v PL/SQL

10. Nh cu 9 hin th thm thng tin v ng KING.


EMP_NAME KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER EMP_SAL MGR_NAME 5000 2850 2450 2975 1250 1600 1500 950 1250 3000 800 3000 1100 1300 KING KING KING BLAKE BLAKE BLAKE BLAKE BLAKE JONES FORD JONES SCOTT CLARK MGR_SAL 5000 5000 5000 2850 2850 2850 2850 2850 2975 3000 2975 3000 2450

11. Hin th ngh nghip c tuyn dng vo nm 1981 v khng c tuyn dng vo nm 1994.

12. Tm nhng nhn vin gia nhp cng ty trc gim c ca h. 13. Tm tt c cc nhn vin, ngy gia nhp cng ty, tn nhn vin, tn ngi gim c v ngy gia nhp cng ty ca ngi gim c y.
EMP_NAME EMP_SAL MGR_NAME 2850 1250 1600 1500 950 1250 2450 1300 2975 3000 800 3300 1100 BLAKE BLAKE BLAKE BLAKE BLAKE BLAKE CLARK CLARK JONES JONES JONES JONES JONES MGR_SAL 2850 2850 2850 2850 2850 2850 2450 2450 2975 2975 2975 2975 2975 BLAKE MARTIN ALLEN TURNER JAMES WARD CLARK MILLER JONES FORD SMITH SCOTT ADAMS 13 rows selected.

14. Tm nhng nhn vin kim c lng cao nht trong mi loi ngh nghip.
JOB ANALYST CLERK MANAGER PRESIDENT SALESMAN MAX(SAL) 3000 1300 2975 5000 1600

15. Tm mc lng cao nht trong mi phng ban, sp xp theo th t phng ban.
ENAME KING JOB PRESIDENT DEPTNO 10 SAL 5000 Trang 48

Oracle c bn - SQL v PL/SQL SCOTT BLAKE SALEMAN MANAGER 20 30 3300 2850

16. Tm nhn vin gia nhp vo phng ban sm nht


ENAME CLARK SMITH ALLEN HIREDATE 09-06-1981 17-12-1980 20-02-1981 DEPTNO 10 20 30

17. Hin th nhng nhn vin c mc lng ln hn lng TB ca phng ban m h lm vic.
EMPNO ENAME 7839 7566 7902 7788 7698 7499 KING JONES FORD SCOTT BLAKE ALLEN SAL 5000 2975 3000 3300 2850 1600 DEPTNO 10 20 20 20 30 30

18. Hin th tn nhn vin, m nhn vin, m gim c, tn gim c, phng ban lm vic ca gim c, mc lng ca gim c.
EMP_NUMBER EMP_NAME EMP_SAL MGR_NUMBER MGR_NAME MGR_DEPT MGR_GRADE 7698 BLAKE 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES 7521 WARD 7782 CLARK 7934 MILLER 7566 JONES 7902 FORD 7369 SMITH 7788 SCOTT 7876 ADAMS 13 rows selected. 2850 1250 1600 1500 950 1250 2450 1300 2975 3000 800 3300 1100 7698 7698 7698 7698 7698 7698 7782 7782 7566 7566 7566 7566 7566 BLAKE BLAKE BLAKE BLAKE BLAKE BLAKE CLARK CLARK JONES JONES JONES JONES JONES 30 30 30 30 30 30 10 10 20 20 20 20 20 4 4 4 4 4 4 4 4 4 4 4 4 4

Trang 49

Oracle c bn - SQL v PL/SQL

Chng 6. BIN RUNTIME


6.1.D LIU THAY TH TRONG CU LNH
Dng (&) ch phn thay th trong cu lnh. Nu dng (&&) ch bin thay th th sau cu lnh bin thay th vn cn tn ti V d 1:
SELECT * FROM emp WHERE &Condition Enter value for condition: sal > 1000

Khi ny cu lnh trn tng ng vi:


SELECT * FROM emp WHERE sal > 1000

V du 2:
Select ename, deptno, job From emp Where deptno = &&depno_please;

6.2.LNH DEFINE
Khai bo v gn tr cho cc bin, v d khai bo bin condition c gi tr 'sal
DEFINE condition = 'sal > 1000'

> 1000'

Khi cu lnh sau khng yu cu nhp vo gi tr cho codition


SELECT * FROM emp WHERE &Condition

loi b bin ra khi b nh dng lnh UNDEFINE. V d:


UNDEFINE condition

lit k cc bin khai bo dng lnh DEFINE m khng ch bin, v d


DEFINE DEFINE CONDITION = 'SAL > 1000'

V d:
DEFINE REM=SAL*12+NVL(COMM,0) SELECT ENAME, JOB, &REM FROM EKP ORDER BY & REM;

Trang 50

Oracle c bn - SQL v PL/SQL

6.3.LNH ACCEPT
Khai bo v gn tr cho bin vi dng hin th
ACCEPT variable [NUMBER/CHAR] [PROMPT/NOPROMPT 'text'] HIDE

V d:
ACCEPT Salary NUMBER PROMPT 'Salary figure: ' Salary figure : 3000

T kho hide cho php che chui nhp liu, hay dng khi nhp password.
ACCEPT password CHAR PROMPT 'Enter password: ' HIDE Password : ***

6.4.BI TP
1. Hin th tn nhn vin, ngy gia nhp cng ty vi iu kin ngy gia nhp cng ty nm trong khong hai bin runtime c nhp vo t bn phm (&first_date, &last_date).

2. Hin th tn nhn vin, ngh nghip, lng, m gim c, m phng ban vi iu kin ngh nghip bng mt bin c nhp vo t bn phm. (&job) 3. nh ngha mt bin tnh thu nhp mt nm ca nhn vin. Dng bin ny tm nhng nhn vin c thu nhp ln hn hoc bng $30000. 4. nh ngha mt bin l khong thi gian nhn vin lm trong cng ty. Hin th tn nhn vin v qung thi gian nhn vin lm vic vi iu kin nhn vin l mt bin c nhp vo t bn phm.
ENAME KING LENGTH OF SERVICE 19 YEAR 4 MONTHS

Trang 51

Oracle c bn - SQL v PL/SQL

Chng 7. TABLE V CC LNH SQL V TABLE


7.1.LNH TO TABLE
7.1.1. C php to bng
to mt bng mi dng lnh CREATE TABLE. C php:
CREATE TABLE tablename (column [datatype][DEFAULT expr][column_constraint]..) [PCTFREE integer][PCTUSED integer] [INITRANS integer][MAXTRANS integer] [TABLESPACE tablespace] [STORAGE storage_clause] [AS subquery]

Vi:
tablename column [datatype] [DEFAULT expr] [column_constraint] [table_constraint] [PCTFREE integer] [PCTUSED integer] [INITRANS integer] [MAXTRANS integer] [TABLESPACE tablespace] [STORAGE storage_clause] Ghi mnh lu tr, n v mc nh l KB trong cc cc chn la l: INITIAL - dung lng khi to; NEXT - dung lng tng tip theo; MINEXTENTS - % m rng nh nht; MAXEXTENTS- % m rng ln nht; PCTINCREASE - Tc tng hng nm. To bng c cu trc ging mnh truy vn Tn table cn to Tn column trong table Kiu d liu ca column Gi tr mc nh ca column trong trng hp NULL l expr Rng buc ca bn thn column Rng buc ca ton bng Phn trm khng gian cn trng Phn trm khng gian s dng S bn ghi khi to S bn ghi ln nht Ch nh TABLESAPCE cho bng

[AS subquery]

V d 1:
CREATE TABLE EMP EMPNO NUMBER NOT NULL CONSTRAINT PK_EMP PRIMARY KEY, ENAME VARCHAR2(10) CONSTRAINT NN_ENAME NOT NULL CONSTRAINT UPPER_ENAME CHECK (ENAME=UPPER(ENAME)), JOB VARCHAR2(9), MGR NUMBER CONSTRAINT FK_MGR REFERENCES SCOTT.EMP(EMPNO), HIREDATE DATE DEFAULT SYSDATE, SAL NUMBER(10,2) CONSTRAINT CK_SAL CHECK(SAL>500), COMM NUMBER(9,0) DEFAULT NULL, DEPTNO NUMBER(2) CONSTRAINT NN_DEPTNO NOT NULL CONSTRAINT FK_DEPTNO REFERENCES SCOTT.DEPT(DEPTNO)) PCTFREE 5 PCTUSED 75

V du 2:
CREATE TABLE SALGRADE1 Trang 52

Oracle c bn - SQL v PL/SQL (GRADE NUMBER CONSTRAINT PK_SALGRADE PRIMARY LOSAL NUMBER, HISAL NUMBER) TABLESPACE USER STORAGE (INITIAL 6144 NEXT 6144 MINEXTENTS 1 MAXEXTENTS 5 PCTINCREASE 5) KEY,

V d 3:
CREATE TABLE DEPT10 AS SELECT EMPNO, ENAME, JOB, FROM EMP WHERE DEPTNO =10;

SAL

V d 4:
CREATE TABLE EMP_SAL (NAME, SALARY,GRADE)AS SELECT ENAME, SAL, GRADE FROM EMP, SALGARDE WHERE EMP.SAL BETWEEN LOSAL AND HISAL ;

to mt table mi, chng ta cn phi chun b mt s thng tin sau: Table phi c chun ha. Nhng column m cho php null nn nh ngha sau tit kim ni lu tr. Gp cc table li nu c th. Ch nh cc thng s pcfree v pctused C th ch nh 2 thng s initstran, maxtrans C th ch nh tablespace cho table C th c lng kch thc table, v cc thng s cho storage.

7.1.2. Tnh ton kch thc table (tham kho)


1. Tnh ton khong a cn thit cho data block header. Tnh theo cng thc sau:
BLOCK HEADER = (FIXED HEADER + VARIABLE TRANSACTION HEADER) + (TABLE DIRECTORY + ROW DIRECTORY)

Trong :
fixed header = 57 bytes variable transaction header = 23*gi tr ca thng s instrans table directory =4 row directory = 2* s lng row trong block.

2. Tnh ton khong a trng cha d liu ca data block. Tnh theo cng thc sau:
Khong a trng cha data =(block size -total block header) (block size -(fixed header+ variable transaction header))*(pctree/100)

C th bit block size bng cch dng lnh


show parameters db_block_size.

Trang 53

Oracle c bn - SQL v PL/SQL

3. Tnh ton khong a trng kt hp bng gi tr ca mi row. 4. Tnh ton kch thc trung bnh ca row:
Kch thc trung bnh ca row = row header +A+B+C A = Tng chiu di ca cc ct <= 250 byte B = Tng chiu di ca cc ct > 250 byte C = Khong a trng kt hp

5. Quyt nh s row trung bnh cho mt block:


avg rows /block = available space/average row size

6. Tnh ton s lng block


Block = s row / s row trung bnh cho mt block

7.2.MT S QUY TC KHI TO TABLE


7.2.1. Quy tc t tn Object
Tn di t 1 n 30 k t, ngoi tr tn CSDL khng qu 8 k t v tn lin kt c th di n 128 k t Tn khng cha du nhy (") Khng phn bit ch hoa ch thng Tn phi bt u bng k t ch trong b k t ca CSDL Tn ch c th cha k t s trong tp k t ca CSDL. C th dng cc k t _, $, #. Oracle khng khuyn khch dng cc k t $ v #. Tn khng c trng vi cc t dng bi Oracle (xemphu lc 1) Tn khng c cch khong trng Tn c th t trong cp du nhy kp, khi tn c th bao gm cc k t bt k, c th bao gm khong trng, c th dng cc t kha ca Oracle, phn bit ch hoa ch thng. Tn phi duy nht trong "khng gian tn" nht nh. Cc object thuc cng khng gian tn phi c tn khc nhau. Cc b danh ca ct, b danh bng, tn ngi s dng, mt khu mc d khng phi l cc object hoc cc thnh phn con ca object nhng cng phi c t tn theo cc quy tc trn, ngoi tr B danh ct, b danh bng ch tn ti khi thc hin cc lnh SQL v khng c lu tr trong CSDL, do vy khng p dng quy tc 9 v khng gian tn. Mt khu khng thuc v khng gian tn no v do cng khng p dng quy tc 9. Nn t tn theo mt quy tc t tn thng nht

7.2.2. Quy tc khi tham chiu n Object C php chung


khi tham chiu n cc object S chung khi tham chiu cc object hoc thnh phn ca cc object
Schema.Object.Part.@dblink

Trong :
object Tn object

Trang 54

Oracle c bn - SQL v PL/SQL schema part dblink Schema cha object Thnh phn ca object Tn CSDL cha object

Oracle gii quyt vic tham chiu cc Object Khi tham chiu n mt object trong cu lnh SQL, Oracle phn tch cu lnh v v xc nh cc object trong khng gian tn. Sau khi xc nh cc object, Oracle thc hin cc thao tc m cu lnh quy nh trn object. Nu tn object truy cp khng thuc khng gian tn th cu lnh khng c thc hin v c thng bo li. Cu lnh sau thm mt mu tin vo bng DEPT
INSERT INTO Dept VALUES (50, 'SUPPOR', 'PARIS')

Theo ng cnh ca cu lnh, Oracle xc nh bng DEPT c th l: Mt table trong schema ca bn Mt view trong schema ca bn ng ngha ring cho table hoc view ng ngha chung cho table hoc view

Tham chiu n cc object khng thuc quyn s hu tham chiu n cc object khng thuc schema hin thi, phi ch ra tn ca schema cha object mun truy cp
schema.object

V d: xa table EMP trong schema SCOTT


DROP TABLE scott.emp

Tham chiu cc object t xa truy cp n mt CSDL xa, sau tn object phi ch ra tn lin kt CSDL (database link) ca CSDL cha object mun truy cp. Database link l mt schema object, Oracle dng thm nhp v truy xut CSDL t xa.

7.3.Cc Kiu d liu c bn


7.3.1. Kiu CHAR
Kiu CHAR dng khai bo mt chui c chiu di c nh, khi khai bo bin hoc ct kiu CHAR vi chiu di ch nh th tt c cc mc tin ca bin hay ct ny u c cng chiu di c ch nh. Cc mc tin ngn hn Oracle s t ng thm vo cc khong trng cho chiu di. Oracle khng cho php gn mc tin di hn chiu di ch nh i vi kiu CHAR. Chiu di ti a cho php ca kiu CHAR l 255 byte

7.3.2. Kiu VARCHAR2


Kiu VARCHAR2 dng khai bo chui k t vi chiu di thay i. Khi khai bo mt bin hoc ct kiu VARCHAR2 phi ch ra chiu di ti a, cc mc tin cha trong bin hay ct kiu VARCHAR2 c chiu di thc s l chiu di ca mc tin. Oracle khng cho php gn

Trang 55

Oracle c bn - SQL v PL/SQL

mc tin di hn chiu di ti a ch nh i vi kiu VARCHAR2. Chiu di ti a kiu VARCHAR2 l 2000 byte.

7.3.3. Kiu VARCHAR


Hin ti Oracle xem kiu VARCHAR2 v VARCHAR l nh nhau, tuy nhin Oracle khuyn nn dng VARCHAR2. Oracle d nh trong tng lai dng kiu VARCHAR cha cc chui vi chiu di bin i, nhng trong php so snh s c ch nh theo nhiu ng ngha khc nhau.

7.3.4. Kiu NUMBER


Kiu s ca Oracle dng cha cc mc tin dng s dng, s m, s vi du chm ng.
NUMBER(p, s) p S ch s trc du chm thp phn (precision), p t 1 n 38 ch s s S cc ch s tnh t du chm thp phn v bn phi (scale), s t -84 n 127

NUMBER(p) S c du chm thp phn c nh vi precision bng p v scale bng 0

NUMBER

S vi du chm ng vi precision bng 38. Nh rng scale khng c p dng cho s vi du chm ng.

V d sau cho thy cch thc Oracle lu tr d liu kiu s ty theo cch nh precision v scale khc nhau. D liu thc
7456123.89 7456123.89 7456123.89 7456123.89 7456123.89 7456123.8 7456123.89 7456123.89

Kiu
NUMBER NUMBER(9) NUMBER(9,2) NUMBER(9,1) NUMBER(6) NUMBER(15,1) NUMBER(7,-2) NUMBER(-7,2)

Gi tr lu tr
7456123.89 7456123 7456123.89 7456123.8 Khng hp l 7456123.8 7456100 Khng hp l

7.3.5. Kiu FLOAT


Dng khai bo kiu s du chm ng, vi chnh xc thp phn 38 hay chnh xc nh phn l 126. FLOAT(b) Khai bo kiu du chm ng vi chnh xc nh phn l b, b t 1 n 126. C th chuyn t chnh xc nh phn sang chnh xc thp phn bng cch nhn chnh xc nh phn vi 0.30103

7.3.6. Kiu LONG


Dng khai bo kiu chui k t vi di bin i, chiu di ti a ca kiu LONG l 2 gigabyte. Kiu LONG thng c dng cha cc vn bn. C mt s hn ch khi dng kiu LONG
Trang 56

Oracle c bn - SQL v PL/SQL

Mt table khng th cha nhiu hn mt ct kiu LONG D liu kiu LONG khng th tham gia vo cc rng buc ton vn, ngoi tr kim tra NULL v khc NULL Khng th index mt ct kiu LONG Khng th truyn tham s kiu LONG cho hm hoc th tc Cc hm khng th tr v d liu kiu LONG Trong cu lnh SQL c truy cp cc ct kiu LONG, th vic cp nht hoc kha cc bng ch cho php trong cng mt CSDL

Ngoi ra, cc ct kiu LONG khng c tham gia trong cc thnh phn sau ca cu lnh SQL Cc mnh WHERE, GROUP BY, ORDER BY, CONNECT BY hoc vi tc t DISTINCT trong cu lnh SELECT Cc hm s dng trong cu lnh SQL nh SUBSTR, INSTR Trong danh sch la chn ca cu lnh SELECT c s dng mnh GROUP BY Trong danh sch la chn ca cu hi con, cu hi c s dng cc ton t tp hp Trong danh sch la chn ca cu lnh CREATE TABLE AS SELECT

7.3.7. Kiu DATE


Dng cha d liu ngy v thi gian. Mc d kiu ngy v thi gian c th c cha trong kiu CHAR v NUMBER. Vi gi tr kiu DATE, nhng thng tin c lu tr gm th k, nm, thng, ngy, gi, pht, giy. Oracle khng cho php gn gi tr kiu ngy trc tip, gn gi tr kiu ngy, bn phi dng TO_DATE chuyn gi tr kiu chui k t hoc kiu s. Nu gn mt gi tr kiu ngy m khng ch thi gian th thi gian mc nh l 12 gi m, Nu gn gi tr kiu ngy m khng ch ra ngy, th ngy mc nh l ngy u ca thng. Hm SYSDATE cho bit ngy v thi gian h thng. Tnh ton i vi kiu ngy i vi d liu kiu ngy, bn c th thc hin cc php ton cng v tr. V d:
SYSDATE+1 ngy hm sau SYSDATE-7 cch y mt tun SYSDATE+(10/1440) mi pht sau

Ngy Julian: L gi tr s cho bit s ngy k t ngy 1 thng ging nm 4712 trc cng nguyn. V d:
SELECT TO_CHAR (TO_DATE('01-01-1992', 'MM-DD-YYYY'), 'J') JULIAN FROM DUAL;

Kt qu:
JULIAN 2448623

Trang 57

Oracle c bn - SQL v PL/SQL

7.3.8. Kiu RAW v kiu LONG RAW


Kiu RAW v LONG RAW dng cha cc chui byte, cc d liu nh phn nh hnh nh, m thanh. Cc d liu kiu RAW ch c th gn hoc truy cp ch khng c thc hin cc thao tc nh i vi chui k t. Kiu RAW ging nh kiu VARCHAR2 v kiu LONG RAW ging kiu LONG, ch khc nhau ch Oracle t ng chuyn i cc gi tr kiu CHAR, VARCHAR2 v LONG gia tp hp k t ca CSDL v tp k t ca cc ng dng.

7.3.9. Kiu ROWID


Mi mu tin trong CSDL c mt a ch c kiu ROWID. ROWID bao gm cc thnh phn:
block.row.file.

Vi
block row file Chui h hexa cho bit block cha row Chui h hexa cho bit row trong block Chui h hexa cho bit database file cha block

V d:
0000000F.0000.0002

Row u tin trong block 15 ca data file th hai.

7.3.10. Kiu MLSLABEL


Kiu MLSLABEL dng cha label dng nh phn m Oracle dng m bo hot ng ca bn thn h thng.

7.3.11. Chuyn i kiu


Chuyn i mc nh Ni chung mt biu thc khng th gm cc gi tr thuc nhiu kiu khc nhau, tuy nhin Oracle cho php chuyn i gi cc kiu d liu. Oracle t ng chuyn kiu ca d liu trong mt s trng hp sau Khi INSERT hoc UPDATE gn gi tr cho ct c kiu khc, Oracle s t ng chuyn gi tr sang kiu ca ct. Khi s dng cc hm hoc cc ton t m cc tham s c kiu khng tng thch th Oracle s t ng chuyn kiu. Khi s dng ton t so snh m cc gi tr c cc kiu khc nhau, Oracle s t ng chuyn kiu.

V d 1:
SELECT ename FROM emp WHERE hiredate = '12-MAR-1993'

Oracle t ng chuyn chui '12-MAR-1993' sang kiu DATE trong php so snh

V d 2:
SELECT ename FROM emp WHERE ROWID = '00002514.0001.0001'

Trang 58

Oracle c bn - SQL v PL/SQL

Oracle t ng chuyn chui '00002514.0001.0001' sang kiu ROWID trong php so snh

Ngi s dng t chuyn i Oracle cung cp cc hm chuyn i kiu, v d TO_NUMBER TO_CHAR TO_DATE Chuyn sang kiu s Chuyn sang kiu k t Chuyn sang kiu ngy

(xem phn tra cu cc hm v th tc)

7.4.RNG BUC D LIU TRONG TABLE


Cc dng constraint gm: NULL/NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY (Referential Key) CHECK

7.4.1. NULL/NOT NULL


L rng buc column trng hoc khng trng. V d mnh rng buc:
CREATE TABLE DEPT ( DEPTNO NUMBER(2) NOT NULL, DNAME CHAR(14), LOC CHAR(13), CONSTRAINT DEPT_PRIMARY_KEY PRIMARY KEY (DEPTNO));

7.4.2. UNIQUE
Ch ra rng buc duy nht, cc gi tr ca column ch trong mnh UNIQUE trong cc row ca table phi c gi tr khc bit. Gi tr null l cho php nu UNIQUE da trn mt ct. V d:
CREATE TABLE DEPT ( DEPTNO NUMBER(2), DNAME CHAR(14), LOC CHAR(13), CONSTRAINT UNQ_DEPT_LOC UNIQUE(DNAME, LOC));

7.4.3. PRIMARY KEY


Ch ra rng buc duy nht (ging UNIQUE), tuy nhin kho l dng kho UNIQUE cp cao nht. Mt table ch c th c mt PRIMARY KEY. Cc gi tr trong PRIMARY KEY phi NOT NULL.

Trang 59

Oracle c bn - SQL v PL/SQL C php khi t CONSTRAINT mc TABLE [CONSTRAINT constraint_name] PRIMARY KEY (column, Column..) C php khi t CONSTRAINT mc COLUMN [CONSTRAINT constraint_name] PRIMARY KEY

7.4.4. FOREIGN KEY ( Referential )


Ch ra mi lin h rng buc tham chiu gia table ny vi table khc, hoc trong chnh 1 table. N ch ra mi lin h cha-con v ch rng buc gia FOREIGN KEY bng ny vi PRIMARY KEY hoc UNIQUE Key ca bng khc. V d quan h gia DEPT v EMP thng qua trng DEPTNO. T kho ON DELETE CASCADE c h nh trong dng kho ny ch khi d liu cha b xo (trong bng DEPT) th d liu con cng t ng b xo theo (trong bng EMP).

7.4.5. CHECK
Rng buc kim tra gi tr. V d:
CREATE TABLE EMP (EMPNO NUMBER NOT NULL CONSTRAINT PK_EMP PRIMARY KEY, ENAME VARCHAR2(10) CONSTRAINT NN_ENAME NOT NULL CONSTRAINT UPPER_ENAME CHECK (ENAME = UPPER(ENAME)), JOB VARCHAR2(9), MGR NUMBER CONSTRAINT FK_MGR REFERENCES SCOTT.EMP(EMPNO), HIREDATE DATE DEFAULT SYSDATE, SAL NUMBER(10,2) CONSTRAINT CK_SAL CHECK(SAL>500), COMM NUMBER(9,0) DEFAULT NULL, DEPTNO NUMBER(2) CONSTRAINT NN_DEPTNO NOT NULL CONSTRAINT FK_DEPTNO REFERENCES SCOTT.DEPT(DEPTNO);

7.5.LNH DDL CAN THIP TI TABLE


7.5.1. Chnh sa cu trc table
Dng lnh ALTER TABLE chnh sa cu trc bng. C php:
ALTER TABLE tablename [ADD/MODIFY/DROP options ([column [column constraint) [ENABLE clause] [DISABLE clause]

Trong :
ADD MODIFY DROP ENABLE/DISABLE Thm column hay constraint. Sa i kiu cc column B constraint. Che khut hoc a vo s dng cc CONSTRAINT m khng xa hn

Ch :

Trang 60

Oracle c bn - SQL v PL/SQL

Kh dng mnh MODIFY khng th chuyn tnh cht ca COLUMN c ni dung l NULL chuyn thnh NOT NULL; Khng th a thm mt ct NOT NUL nu table c s liu. Phi thm ct NULL, in y s liu, sau chuyn thnh NOT NULL. Khng th chuyn i kiu khc nhau nu column cha s liu Khng th dng mnh MODIFY nh ngha cc CONSTRAINT tr rng buc NULL/NOT NULL. Mun sa CONSTRAINT cn xo chng sau ADD thm vo.

V d 1:
ALTER TABLE emp ADD (spouse_name CHAR(10);

V d 2:
ALTER TABLE emp MODIFY (ename CHAR(25);

V d 3:
ALTER TABLE emp DROP CONSTRAINT ALTER TABLE DROP PRIMARY KEY; emp_mgr;

V d 4:
ALTER TABLE dept DISABLE CONSTRAINT dept_prim;

7.5.2. Cc lnh DDL khc


Xa table Dng lnh DROP TABLE xo bng. C php:
DROP TABLE table_name [CASCADE CONSTRAINTS]

Trong :
CASCADE CONSTRAINTS xa tt c cc rng buc ton vn lin quan n table b xa.

V d:
DROP TALE emp

Khi drop table th: Xa tt c d liu View v synonymlin quan vn cn nhng khng c gi tr Cc giao dch cha gii quyt xong s c commit Ch ngi to ra table hay DBA mi c th xa table

7.5.3. Ch dn cho table


Dng lnh COMMENT ch thch. V d:

Trang 61

Oracle c bn - SQL v PL/SQL COMMENT ON TABLE EMP IS THONG TIN NHAN VIEN; COMMENT ON COLUMN EMP.EMPNO IS MA SO NHAN VIEN;

7.5.4. Thay i tn object


Dng lnh RENAME thay i tn object. C php:
RENAME old TO new

Trong :
old new Tn c Tn mi

V d:
RENAME emp TO employee

7.5.5. Xa d liu ca table


Dng lnh TRUNCATE TABLE xa d liu ca table, xa tt c cc row trong table. C php:
TRUNCATE TABLE table_name [REUSE STORAGE]

Trong :
REUSE STORAGE gi li khung cha, ch xa d liu

7.6.THNG TIN V TABLE TRONG T IN D LIU


Trung tm ca c s d liu Oracle l data dictionary. Data dictionary t ng c to ra khi c s d liu Oracle c to. Oracle cp nht ln data dictionary bng cc lnh DDL (Data Define Language). Cc table ca t in d liu c to ra bng lnh CREATE DATABASE v ch c to t user SYS. Cc view trong t in d liu chc cc thng tin di dng d nhn hn bng. C cc dng view l: USER_xxx: l nhng i tng thuc user. V d cc bng c to bi user ALL_xxx: l tt c cc i tng m user c quyn truy nhp DBA_xxx: tt c cc i tng trong database V$: Cc thc thi ca Server.

Ngoi ra cn c cc view quan trng khc l: DICTIONARY: Thng tin v ton b cc table, view, snapshot trong t in d liu TABLE_PRIVILEGES: Thng tin v vic gn quyn trn cc i tng IND: ng ngha ca USER_INDEX.

Mun hin th ton b thng tin v cc table, view, snapshot trong t in d liu dng lnh
SELECT * FROM DICTIONARY;

Trang 62

Oracle c bn - SQL v PL/SQL

Hin th cu ca USER_OBJECT
DESCRIBE USER_OBJECT;

Hin th tt c cc bng m user s hu:


SELECT OBJECT_NAME FROM USER_OBJECT WHERE OBJECT_TYPE = TABLE; SELECT * FROM TAB; SELECT TABLE_NAME FROM USER_TABLE;

Hin th tt c cc loi i tng trong t in d liu:


SELECT DISTINCT OBJECT_TYPE FROM USER_OBJECTS;

7.7.BI TP
1. To bng PROJECT vi cc column c ch ra di y, PROJID l promary key, v P_END_DATE > P_START_DATE.
Column name PROJID P_DESC P_START_DATE P_END_DATE BUDGET_AMOUNT MAX_NO_STAFF Data Type Size. NUMBER VARCHAR2 DATE DATE NUMBER NUMBER 4 20 7,2 2

2. To bng ASSIGNMENTS vi cc column c ch ra di y, ng thi ct PROJID l foreign key ti bng PROJECT, ct EMPNO l foreign key ti bng EMP.
Column name PROJID EMPNO A_START_DATE A_END_DATE BILL_AMOUNT ASSIGN_TYPE Data Type Size. NUMBER NUMBER DATE DATE NUMBER VARCHAR2 4 4 4,2 2 NOT NULL NOT NULL

3. Thm column COMMENTS kiu LONG vo bng PROJECTS. Thm column HOURS kiu NUMBER vo bng ASSIGNMENTS. 4. S dng view USER_OBJECTS hin th tt c cc i tng user s hu. 5. Thm rng buc duy nht (UNIQUE) cho 2 column PROJECT_ID v EMPNO ca bng ASSIGNMENTS. 6. Xem cc thng tin v cc rng buc trong USER_CONSTRAINTS. 7. Xem trong USER hin ti c tt c bao nhiu bng.
Trang 63

Oracle c bn - SQL v PL/SQL

Chng 8. CC LNH THAO TC D LIU


8.1.THAO TC D LIU TRONG TABLE
8.1.1. Thm mi dng d liu
chn mt row vo table dng lnh INSERT. C php:
INSERT INTO tablename ([column, VALUES (value, value ...); column, ...])

V d:
INSERT INTO dept (depno, dname, loc) VALUES (50, 'MARKETING', 'SAN JOSE')

Chp d liu t table khc


INSERT INTO table [(column, column...)] SELECT select_list FROM table(s)

V d:
INSERT INTO emp_tmp (ename, sal) SELECT ename, sal FROM emp WHERE sal > 1000

Bt u t phin bn Oracle 9i, ta c th thm mi dng d liu v t gi tr mc nh thng qua t kho DEFALT V d: INSERT INTO EMP (EMPNO, ENAME, DEPTNO) VALUES (8000,MIKE,DEFAULT);

Oracle 9i cn cho php thc hin lnh INSERT trn ng thi nhiu table khc nhau, ch s dng mt cu lnh DML. V d: Lnh INSERT khng iu kin (UNCONDITIONAL) INSERT ALL INTO T1 (C1, C2, ...) VALUES (C1, C2, ...) INTO T2 (C1, C2, ...) VALUES (C1, C2, ...) SELECT C1, C2, ... FROM T9;

Lnh INSERT khng iu kin (CONDITIONAL) INSERT [ALL|FIRST] WHEN c1 = 1 THEN INTO T1 (C1, C2, ...) VALUES (C1, C2, ...) WHEN c1 = 2 THEN INTO T2 (C1, C2, ...) VALUES (C1, C2, ...) WHEN c2 = 3 THEN INTO T3 (C1, C2, ...) VALUES (C1, C2, ...) SELECT C1, C2, ... FROM T9;
Trang 64

Oracle c bn - SQL v PL/SQL

FIRST: insert cho cu lnh u tin c gi tr iu kin ng ALL: insert cho mi cu lnh c gi tr iu kin l ng

8.1.2. Cp nht dng d liu


chnh sa d liu dng lnh UPDATE. C php:
UPDATE table [alias] SET column [,column...] [WHERE condition] = [expr, subquery]

V d 1:
UPDATE emp SET job = 'SALEMAN', hiredate = sysdate, sal = sal * 1.1 WHERE ename = 'SCOTT';

V d 2:
UPDATE emp SET comm = (SELECT comm FROM commission C WHERE C.empno = emp.empno) WHERE empno IN (SELECT empno FROM commission);

V d 3:
UPDATE emp a SET deptno = (SELECT deptno FROM dept WHERE loc = 'BOSTON'), (sal, comm) = (SELECT 1.1*AVG(sal),1.5*AVG(comm) FROM emp b WHERE a.deptno = b.deptno) WHERE deptno IN (SELECT deptno FROM dept WHERE loc = 'DALLAS' OR loc = 'DETROIT');

Ta cng c th s dng mnh DEFAULT trong cu lnh cp nht d liu V d: UPDATE EMP SET COMM = DEFAULT;

Ch thch:
- Cp nht cc nhn vin Dallas hoc Detroit - Thay DEPTNO ca cc nhn vin ny bng DEPTNO ca Boston - Thay lng mi nhn vin bng lng trung bnh ca b phn * 1.1 - Thay commission ca mi nhn vin bng commission trung bnh ca b phn * 1.5

8.1.3. Lnh Merge


Lnh MERGE l mt c im rt hay ca Oracle 9i. N cn c gi l lnh UPSERT, tc l c kh nng va thc hin vic Update, va thc hin lnh Insert tu vo bn ghi ch c tn ti hay khng. C php: MERGE INTO T1

Trang 65

Oracle c bn - SQL v PL/SQL

USING T2 ON (T1.C9=T2.C9) WHEN MATCHED THEN UPDATE SET T1.C1=T2.C2, T1.C2=T2.C2 ... WHEN NOT MATCHED THEN INSERT (C1,C2, ...) VALUES (C1,C2, ...);

8.1.4. Xa dng d liu


xa dng dng lnh DELETE. C php:
DELETE FROM table [WHERE condition]

V d:
DELETE FROM emp WHERE deptno = 10;

8.1.5. Li rng buc d liu


Thng thng khi thc hin cc lnh thao tc d liu hay gp phi cc li rng buc ton vn d liu. Cc li ny xut hin khi c cc rng buc trc m d liu nhp vo, chnh sa hay khi xo i khng m bo cc iu kin ton vn. M li: ORA_02292: INTEGRITY CONSTRAINT. Sau bo tn ca Constraint b li.

8.2.LNH IU KHIN GIAO DCH


Mt cu lnh SQL c th gm Lnh DML thao tc d liu Lnh DDL nh ngha d liu Lnh DCL iu khin truy nhp d liu Mt giao dch bt u khi mt lnh SQL c thc hin Mt giao dch kt thc mt trong cc trng hp sau: COMMIT hoc ROLLBACK Cc lnh DDL v DCL thc hin (t ng commit) Li, thot khi SQL*Plus, h thng b down.

C php: Kt thc giao dch hin ti, thc hin cc chuyn i d liu
COMMIT

Xc nh im savepoint ca giao dch


SAVEPOINT name

Quay li d liu im SAVEPOINT hoc ton b giao dch.


ROLLBACK [TO SAVEPOINT name]

Trang 66

Oracle c bn - SQL v PL/SQL

T ng COMMIT

khi thc hin cc lnh Insert, update, delete.

SET AUTO[COMMIT] ON/OFF

V d:
INSERT INTO DEPT VALUES (50,TESTING,LAS VEGAS); SAVEPOINT INSERT_DONE; UPDATE DEPT SET DNAME = MARKETING; ROLLBACK TO INSERT_DONE ; UPDATE DEPT SET DNAME WHERE DNAME =SALES; COMMIT; = MARKETING

8.3.BI TP
1. Thm d liu vo bng PROJECTS.
PROJID P_DESC P_START_DATE P_END_DATE BUDGET_AMOUNT MAX_NO_STAFF 1 WRITE C030 COURSE 02-JAN-88 07-JAN-88 500 1 2 PROOF READ NOTES 01-JAN-89 10-JAN-89 600 1

2. Thm d liu vo bng ASSIGNMENTS.


PROJID EMPNO A_START_DATE A_END_DATE BILL_RATE ASSIGN_TYPE HOURS 1 7369 01-JAN-88 03-JAN-88 50.00 WR 15 1 7902 04-JAN-88 07-JAN-88 55.00 WR 20 2 7844 01-JAN-89 10-JAN-89 45.50 PF 30

3. Cp nht trng ASIGNMENT_TYPE t WT thnh WR.

4. Nhp thm s liu vo bng ASSIGNMENTS.

Trang 67

Oracle c bn - SQL v PL/SQL

Chng 9. SEQUENCE V INDEX


9.1.SEQUENCE
9.1.1. To Sequence
Sequence l danh sch tun t ca con s, v c to bi Oracle sever. Sequence dng to kha chnh mt cch t ng cho d lu. Sequence thng dng to kha chnh trong sinh m t ng. C th dng chung cho nhiu i tng. Con s sequence ny c chiu di ti a l 38 s. to sequence, dng lnh CREATE SEQUENCE C php:
CREATE SEQUENCE sequence_name INCREMENT BY integer START WITH integer [MAXVALUE integer] [MINVALUE integer] [CYCLE/NO CYCLE];

Vi:
INCREMENT BY START WITH MAXVALUE MINVALUE CYCLE/NO CYCLE Ch Ch Gi Gi Dy Mc nh khong cch ca nh s u tin ca tr ln nht ca dy tr nh nht ca dy tun t c quay vng nh l NO CYCLE dy s tun t dy s tun t tun t tun t khi n im cui.

V d:
CREATE SEQUENCE sample_sequence INCREMENT 1 STRAT WITH 2 MAXVALUE 100;

lm vic vi cc sequence, dng lnh SQL vi cc ct gi sau


CURRVAL NEXTVAL Cho gi tri hin thi ca sequence Tng gi tri hin thi ca sequence v cho gi tr sau khi tng phi xc nh tn sequence trc currval v nextval

sequence.CURRVAL sequence.NEXTVAL

truy cp cc sequence khng thuc schema hin thi, th phi ch ra tn schema


schema.sequence.CURRVAL schema.sequence.NEXTVAL

truy cp cc sequence t xa, th cn phi ch ra datalink


schema.sequence.CURRVAL@dblink schema.sequence.NEXTVAL@dblink

Trang 68

Oracle c bn - SQL v PL/SQL

S dng sequence CURRVAL v NEXTVAL c th c s dng trong cc trng hp sau: Trong danh sch la chn ca cu lnh SELECT Trong mnh VALUES ca cu lnh INSERT Trong mnh SET ca cu lnh UPDATE Khng c s dng CURRVAL v NEXTVAL trong cc trng hp sau Trong cu hi con Trong cc view v snapshot Trong cu lnh SELECT c tc t DISTINCT Trong cu lnh SELECT c s dng GROUP BY hay ORDER BY Trong cu lnh SELECT c s dng cc php ton tp hp nh UNION, INTERSET, MINUS Trong mnh WHERE ca cu lnh SELECT Ga tr DEFAULT ca ct trong cu lnh CREATE TABLE hay ALTER TABLE Trong iu kin ca rng buc CHECK

9.1.2. Thay i v hu sequence


Thay i sequence:
ALTER SEQUENCE sequence_name INCREMENT BY integer START WITH integer [MAXVALUE integer] [MINVALUE integer] [CYCLE/NO CYCLE];

Hu sequence:
DROP SEQUENCE sequence_name ;

9.2.INDEX
9.2.1. To index
Index l mt cu trc c s d liu, c sever s dng tm mt row trong bng mt cch nhanh chng. Index bao gm mt key value (mt ct (column) trong hng (row)) v ROWID. C php:
CREATE [UNIQUE]] INDEX index_name ON TABLE ( column [,column...]);

9.2.2. S dng index


Ta s dng index trong mt s trng hp sau: Dng index query cho nhanh. Dng Index khi m vic ly d liu <15% s row trong bng. Index nhng column no dng ni gia cc bng ln nhau. Khng nn dng Index cho cc bng no ch c vi row. Primaryv unique key ( kha chnh v kha duy nht) t ng c index, nhng nn c index cho foreign key( kha ngoi).

Trang 69

Oracle c bn - SQL v PL/SQL

S lng index cho mt table l khng gii hn. Tuy nhin nu c qu nhiu index s gy nh hng n s liu khi m d liu trong table b thay i th t theo index. V d: Thm mt row vo bng tt c cc Index s c update. Nn chn la gia yu cu query, v insert, update c mt index hp l. i vi cc kho PRIMARY KEY v UNIQUE KEY t kho UNIQUE c t ng thm khi to INDEX. V d:
CREATE INDEX i-ENAME ON EMP (ENAME);

Xo INDEX bng lnh:


DROP INDEX index_name ;

9.3.BI TP
1. To Index trn ct PROJID cho bng ASSIGNMENT. 2. Hin th danh sch ca nhn vin thuc s qun l ca ngi c tn l 1 bin c nhp t bn phm
EMPNO ENAME JOB 7698 7654 7499 7844 7900 7521 MGR HIREDATE SAL COMM 2850 1250 1600 1500 950 1250 1400 300 0 500 DEPTNO 30 30 30 30 30 30 BLAKE MANAGER 7839 01-05-1981 MARTIN SALESMAN 7698 28-09-1981 ALLEN SALESMAN 7698 20-02-1981 TURNER SALESMAN 7698 08-09-1981 JAMES CLERK 7698 03-12-1981 WARD SALESMAN 7698 22-02-1981

Trang 70

Oracle c bn - SQL v PL/SQL

Chng 10. VIEWS


10.1.VIEWS
10.1.1. To view
View l mt table logic, view khng phi l ni lu tr d liu mc vt l. Cc thnh phn ca view da trn table hoc l trn view khc. Mi tc ng ln view u gy nh hng ti table ca view , v ngc li. nh ngha mt view dng query trn mt bng hay mt view no . C php:
CREATE [OR REPLACE] [FORCE] VIEW view_name [(column, column,...)] AS SELECT statement [WITH CHECK OPTION [CONSTRAINT constraint_name]];

Trong :
OR REPLACE FORCE column, column WITH CHECK OPTION to view chn ln view cng tn to view c khi table hay view no khng tn ti trong cu lnh SELECT. Tn cc column ca view Nu c lnh insert hoc update ln vie, ql s kim tra iu kin ph hp trong mnh where ca view. Nu khng d liu s ch kim tra cc rng buc ton vn ca bng. Ch ra tn ca iu kin kim tra.

CONSTRAINT

V d 1:
CREATE VIEW emp_view AS SELECT empno, ename, sal FROM emp WHERE deptno = 10;

V d 2:
CREATE VIEW dept_summary (name, minsal, maxsal, avsal) AS SELECT dname, min(sal), max(sal), avg(sal) FROM emp, dept FROM emp, dept WHERE emp.deptno = dept.deptno GROUP BY dname;

V d 3:
CREATE VIEW dept_view AS SELECT eame, sal*12 Annsal FROM emp WHERE deptno = 20 WITH CHECK OPTIION CONSTRAINT dept_check;

10.1.2. Xa cc view
Ch nhng ngi to view mi c quyn DROP
Trang 71

Oracle c bn - SQL v PL/SQL DROP VIEW dept_view;

View c th thc hin cc lnh SQL sau: SELECT INSERT (insert trn view cng nh hng ln table) Update (nh hng ln table) Comment

Tuy nhin c nhng rng buc sau: Khng th insert, update trn view, khi query ca view cha cc ton t join, set, distinct, group by, group. Khng th no insert, update trn view, nu nh trong view c dng with check option. Khng th no insert trn view, trn table c nhng ct not Null m khng dng default value ( bi v trong trng hp ny view s c t colunm hn table table. Nn insert 1 row vo view, thc cht l insert row vo table s khng hp l). Khng th no insert trn view, nu view ny c dng biu thc decode. Nhng query ca view khng th no tham kho vo 2 column gi nextval, currval (nextval, currval dng cho sequence).

10.2.BI TP
1. To view c hin th nh sau:
select * from aggredates; DEPTNO AVERAGE MAXIMUN 5000 3300 2850 MINIMUN 1300 800 950 SUM 8750 11175 9400 NO_SALS NO_COMMS 3 5 6 0 0 4

10 2916.66667 20 2235 30 1566.66667

2. To view nhp s liu vo bng ASIGNMENT vi cc iu kin sau:


PROJID <2000, P_START_DATE<P_END_DATE

Cc gi tr c th chp nhn ca assign_type l PS, WT hoc ED


EMPNO c gi tr NOT NULL BILL_RATE < 50 Vi ASSIGN_TYPE L PS BILL_RATE < 60 Vi ASSIGN_TYPE L WT BILL_RATE < 70 Vi ASSIGN_TYPE L ED

3. nh ngha bng MESSAGES c cu trc


Column name Data Type NUMCOL1 NUMCOL2 CHARCOL1 CHARCOL2 DATECOL1 DATECOL2 NUMBER(9,2) NUMBER(9,2) VARCHAR2(60) VARCHAR2(60) DATE DATE

Trang 72

Oracle c bn - SQL v PL/SQL

Chng 11. QUYN V BO MT


11.1.QUYN - PRIVILEGE
Privileges l cc quyn hn c thc hin cc thao tc hoc thc hin vic truy nhp n cc i tng d liu. Trong Oracle bn s khng th thc hin c cc thao tc m khng c cc quyn tng ng. Cc quyn hn ny c gn cho User c th thc hin cc thao tc trn cc i tng ch nh. Vic gn quyn c thc hin bi ngi qun tr c s d liu. Gn quyn hoc loi b: thc hin gn quyn cho mt i tng dng lnh Grant loi b quyn hn dng Revoke (hoc bng cc cng c h tr khc nh Oracle Enterprise manager) Cc quyn bao gm: Bo mt CSDL Bo mt h thng Bo mt d liu Quyn h thng: Quyn truy nhp v CSDL Quyn trn i tng: Thao tc ni dung ca cc i tng CSDL Schema l tp howpjc c i tng nh tables, view... CSDL: Khi ci t xong h qun tr CSDL Oracle mc nh c 2 user. SYS: C quyn cao nht. Mt khu l change_on_install SYSTEM: C quyn thp hn SYS. Mt khu l MANAGER

Quyn h thng Trong cc quyn h thng quyn DBA l ln nht. DBA c quyn CREATE USER : To user mi DROP USER :Xo user DROP ANY TABLE :Xo table BACKUP ANY TABLE :To cc backup table.

Lnh to user ca ngi c quyn DBA nh sau:


CREATE USER user_name IDENTIFY BY password;

Quyn trn i tng: CREATE SESION: Truy nhp vo CSDL CREATE TABLE: to bng trong user CREATE SEQUENCE: To sequence CREATE VIEW: To view CREATE PROCEDURE: To procedure Gn quyn
Trang 73

Oracle c bn - SQL v PL/SQL GRANT privilege[,privilege...] TO user [,user...]

Xo quyn
REVOKE privilege[,privilege...] FROM user [,user...]

11.2.ROLE
Role l tn ca mt nhm cc quyn hn. N c to qun l quyn hn cho cc ng dng hoc nhm cc User. Vic dng role cho php qun l thng nht trn cc i tng, tng tnh mm do trong qun tr, d dng thay i. V d hai i tng X, Y c quyn trn role A tc l role A c quyn g th X, Y c quyn tng ng khi role A b thay i quyn hn th X, Y cng b thay i quyn hn theo.

Lnh to Role C php:


CREATE ROLE role [IDENTIFY BY password];

Gn privilege cho Role Gn Role c cc i tng Mt s Role hay dng: CONNECT RESOURCE

Lnh gn v xo Role ging nh lnh gn v xo Privilege. Chi tit xem trong phn qun tr Oracle.

11.3.SYNONYM
Synonyms l b danh cho mi i tng ca Oracle. Cc i tng ca Oracle l table, view, snapshot, sequence, procedure, function, package v cc synonym khc. C php
CREATE PUBLIC SYNONYM synonym_name FROM [OWNER.]object_name;

Dng Synonyms c nhng li im sau: Khng tn thm ni lu tr khc bi v n c ct trn t in d liu. Lm n gin on chng trnh SQL. Tng tnh bo mt cho database. C th cho php mi ngi (public) truy xut cc i tng ca Oracle.

V d: Chng ta c mt table EMPLY trong schema emp_01 Khi lp trnh th phi truy xut theo emp_01. EMPLY, tn di nh vy th on chng trnh s di s d lm ln. Nn chng ta phi dng synonym
CREATE SYNONYM EMP FOR EMP_01.EMPLY;

Trang 74

Oracle c bn - SQL v PL/SQL

C th to mt synonym cho php mi ngi c th tham kho ti


CREATE PUBLIC EMP FOR EMP_01.EMPLY;

Tnh bo mt l v synonym l b danh, nn ngi s dng dng b danh ny s khng on c thm thng tin g.

Trang 75

Oracle c bn - SQL v PL/SQL

Chng 12. GII THIU NGN NG PL/SQL


12.1.TNG QUAN V PL/SQL
12.1.1. C php lnh PL/SQL
Mi lnh SQL kt thc bng du (;) Lnh nh ngha CSDL (DDL) khng c s dng trong PL/SQL Lnh SELECT tr v nhiu dng c th gy exception Lnh DML c th tc ng trn nhiu dng V d:
x := 1; INSERT INTO emp (id, name) VALUES (50, GARNOR); BEGIN SELECT name FROM dept INTO :DEPT.NAME; EXCEPTION WHEN others THEN Message(SQLERRM); END; UPDATE emp SET sal := sal*1.2 WHERE dept_id = 10;

12.1.2. Khi lnh PL/SQL


Ngn ng PL/SQL t chc cc lnh theo tng khi lnh. Mt khi lnh PL/SQL cng c th c cc khi lnh con khc trong n. Cu trc y ca mt khi lnh PL/SQL bao gm:
DECLARE /* Phn khai bo - Khng bt buc */ Khai bo cc bin s dng trong phn thn BEGIN /* Phn thn */ on lnh thc hin; EXCEPTION /* Phn x l li - Khng bt buc */ X l li xy ra; END;

V d1:
DECLARE empno BEGIN UPDATE emp SET sal = 9000 WHERE empno = 0001; END; NUMBER(4):=7788;

V d 2:
DECLARE v_deptno v_loc BEGIN NUMBER(2); VARCHAR2(15);

Trang 76

Oracle c bn - SQL v PL/SQL SELECT deptno, loc INTO v_deptno, v_loc FROM dept WHERE dname = 'SALES'; EXCEPTION WHEN others THEN Message(SQLERRM); END;

12.2.LNH LP TRNH PL/SQL N GIN


12.2.1. Lnh IF
Thc hin cu lnh theo iu kin. C php:
IF <iu kin 1> THEN Cng vic 1; [ELSIF <iu kin 2> THEN Cng vic 2; ]

[ELSE Cng vic n + 1; ] END IF;

V d 1:
IF ename = 'SCOTT' THEN beam_me_up := 'YES'; COMMIT; ELSE beam_me_up := 'NO'; ROLLBACK; END IF;

V d 2:
IF choice= 1 THEN action := 'Run payroll'; ELSIF choice=2 THEN action:='Run'; ELSIF choice=3 THEN action:='Backup'; ELSE action:='Invalid'; END IF; Trang 77

Oracle c bn - SQL v PL/SQL

12.2.2. Lnh lp LOOP khng nh trc


Trong lnh lp ny, s ln lp tu thuc vo iu kin kt thc vng lp v khng xc nh c ngay ti thi im bt u vng lp. C php:
LOOP Cng vic; EXIT WHEN iu kin; END LOOP;

V d:
x := 0; y := 1000; LOOP x := x + 1; y := y - x; EXIT x > y; END LOOP;

12.2.3. Lnh lp LOOP c nh trc


Ngay khi bt u vng lp, ta xc nh c s ln lp. C php:
LOOP Index IN Cn di .. Cn trn Cng vic; END LOOP;

V d:
x := 0; LOOP Index IN 1 .. 100 x := x + 1; END LOOP;

12.2.4. Lnh lp WHILE


C php:
WHILE iu kin LOOP Cng vic; END LOOP;

V d:
WHILE length(:Address) < 50 LOOP :Address := :Address || ; END LOOP;

12.2.5. Lnh GOTO, nhy v iu kin


C php:
GOTO Nhn; Trang 78

Oracle c bn - SQL v PL/SQL

V d:
BEGIN <<Nhn>> cng vic; GOTO Nhn; END;

12.3.GII THIU CURSOR


Cursor l kiu bin c cu trc, cho php ta x l d liu gm nhiu dng. S dng ph thuc vo cu lnh truy vn d liu sau n. Trong qu trnh x l, ta thao tc vi cursor thng qua tng dng d liu. Dng d liu ny c nh v bi mt con tr. Vi vic dch chuyn con tr, ta c th ly c ton b d liu tr v. Cc bc s dng bin cursor:
Khai bo --> m cursor --> ly d liu x l --> ng cursor

Khai bo:
CURSOR Tn cursor( danh sch bin) IS Cu lnh truy vn;

V d1:
CURSOR c_Dept IS SELECT deptno, dname FROM dept WHERE deptno>10;

V d2:
CURSOR c_Dept(p_Deptno NUMBER) SELECT deptno, dname FROM dept WHERE deptno>10; IS

M cursor:
OPEN Tn cursor | Tn cursor( danh sch bin);

V d1:
OPEN c_Dept;

V d2:
OPEN c_Dept(10);

Ly d liu:
FETCH Tn cursor INTO Tn bin;

V d:
FETCH c_Dept INTO v_Dept;

ng cursor:
CLOSE Tn cursor;

V d:
CLOSE c_Dept;

Cc thuc tnh:
%isopen tr li gi tr True nu cursor ang m

Trang 79

Oracle c bn - SQL v PL/SQL %notfound %found %rowcount tr li tr row tr li gi tr True nu lnh fetch hin thi tr khng c row li gi tri true cho n khi fetch khng cn no li s row c thc hin bng lnh fetch

V d1:
DECLARE -- Khai bo cursor truy vn d liu CURSOR c_Emp IS SELECT * FROM emp WHERE dept_id = 10; -- Khai bo bin cursor tng ng cha dng d liu v_Emp c_EMP%rowtype; BEGIN -- M cursor OPEN c_Emp; LOOP -- Ly dng d liu t cursor FETCH c_Emp INTO v_Emp; -- Thot khi vng lp nu ly ht d liu trong cursor EXIT WHEN c_Emp%notfound; -- B sung d liu vo Emp_ext theo d liu ly c t cursor INSERT INTO Emp_ext (empno, ename, job) VALUES (v_Emp.empno, v_Emp.ename, v_Emp.job); END LOOP; -- ng cursor CLOSE c_Emp; END;

V d 2:
DECLARE -- Khai bo cursor, c cho php cp nht d liu CURSOR c_Dept IS SELECT dname, loc FROM dept FOR UPDATE OF loc; -- Khai bo bin lu tr d liu v_Dept c_Dept%ROWTYPE; v_sales_count NUMBER:=0; v_non_sales NUMBER:=0; BEGIN -- M cursor OPEN c_Dept; LOOP -- Ly tng dng d liu ca cursor x l FETCH c_Dept INTO v_Dept; -- Thot khi lnh lp nu duyt ht tt c d liu EXIT WHEN c_Dept %notfound; IF (v_Dept.dname = 'SALES')AND(v_Dept.loc!='DALLAS') THEN -- Cp nht d liu trn cursor

Trang 80

Oracle c bn - SQL v PL/SQL UPDATE Dept SET loc='DALLAS' WHERE CURRENT OF c_Dept; -- m s lng bn ghi c cp nht v_sales_count := sales_count + 1; ELSIF (v_dept.dname != 'SALES')AND(v_Dept.loc!='NEWYORK') THEN -- Cp nht d liu trn cursor UPDATE Dept SET loc = 'NEWYORK' WHERE CURRENT OF c_Dept; -- m s lng bn ghi c cp nht v_non_sales := v_non_sales + 1; END IF; END LOOP; -- ng cursor CLOSE c_Dept; -- Lu gi cc thng s va xc nh vo bng INSERT INTO counts (sales_set, non_sales_set) VALUES (v_sales_count, v_non_sales); -- Ghi nhn cc thay i d liu trn COMMIT; END;

12.4.CC KIU D LIU THNG DNG


12.4.1. Kiu d liu Table
C php:
TYPE Tn_kiu_Table IS TABLE OF Tn kiu d liu [NOT NULL] INDEX BY BINARY_INTEGER; Tn bin Tn_kiu_Table;

V d:
TYPE t_Name IS TABLE OF Emp.Ename%TYPE INDEX BY BINARY_INTEGER; v_First_name v_Last_name t_Name; t_Name;

12.4.2. Kiu d liu Record


C php:
TYPE Tn_kiu_Record IS RECORD OF ( Col1 Col2 Tn bin

Tn kiu [NOT NULL{:=|DEFAULT} biu thc], Tn kiu [NOT NULL{:=|DEFAULT} biu thc]...);

Tn_kiu_Record;

V d:
TYPE t_Emp IS RECORD OF ( empno

number(4) not null,

Trang 81

Oracle c bn - SQL v PL/SQL ename job mgr hiredate sal comm deptno v_Emp_record t_Emp; char(10), char(9), number(4), date default sysdate, number(7,2), number(7,2), number(2) not null);

12.4.3. Sao kiu d liu mt dng


Bn ghi trong PL/SQL. l mt bin c th gi nhiu gi tr v l mt tp hp cc bin tng ng vi cc trng trong table. Khai bo kiu d liu bn ghi.
Tn bin Tn bng%ROWTYPE;

V d:
v_Emp emp%ROWTYPE;

Truy nhp n cc trng trong d liu bn ghi dng ging nh trong 1 dng d liu tr v. V d:
v_Emp.empno, v_Emp.sal, ...

12.4.4. Sao kiu d liu ca mt ct


C php:
Tn bin Tn ct d liu%TYPE; Emp.sal%TYPE;

V d:
v_Sal

12.4.5. Lnh SELECT... INTO


C php:
SELECT col1, col2... INTO var1, var2... [cursor_var] FROM table1, table2... [WHERE condition1, condition2... ] [GROUP BY col1, col2 ...] [HAVING condition1, condition2...] [FOR UPDATE];

Vi:
INTO var1, var2... [cursor_var] Bin lu gi cc gi tr trong table ly t lnh select.

V d:
SELECT deptno, loc INTO v_deptno, v_loc FROM dept WHERE dname = SALES;

Trang 82

Oracle c bn - SQL v PL/SQL

12.5.BI TP
1. Vit on chng trnh tm kim cc hng trong bng EMP vi bin c a t ngoi vo l &1 dng JOb_type(emp.job%type) v a ra thng bo thch hp vo bng MESSAGES. 2. Vit on chng trnh ghi d liu vo bng MESSAGES vi ct NUMCOL1 mang gi tr l 1 nu l row 1 c Insert, 2 nu row 2 c Insert... . Khng c Insert nhng row c gi tr l 6 hoc 8, thot khi vng lp insert sau gi tr 10. Commit sau vng lp. 3. Lit k cc ct ENAME, HIREDATE, SAL Vi iu kin EMPNO bng gi tr bin &EMPLOYEE_NO c a vo, sau kim tra:

1.1 1.2 1.3

C phi mc lng ln hn 1200 Tn nhn vin c phi c cha ch T ngy gia nhp c quan c phi l thng 10 (DEC)

v a gi tr kim tra ny vo bng message ct charcol1 (th vi cc gi tr 7654, 7369, 7900, 7876) 4. a vo vng lp v t 1 n 10 lnh: UPDATE messages SET numcol2=100 WHERE numcol1 = v; nu bt k mt ln update no c s lng row >1 th exit khi vng lp.

Trang 83

Oracle c bn - SQL v PL/SQL

Chng 13. GII THIU PROCEDURE BUILDER


Procedure builder l mt thnh phn c tch hp vo mi trng pht trin ng dng ca Oracle. N cho php ngi s dng c th son tho, bin dch, kim tra v d li i vi cc hm, th tc hay package vit bi ngn ng PL/SQL c Client v Server.

13.1.CC THNH PHN TRONG PROCEDURE BUILDER


Thnh phn Object Navigator PL/SQL Interpreter Program Unit Editor Din gii iu khin truy nhp cc hm, th tc PL/SQL. Thc hin thao tc d li (debug) trn cc khi lnh SQL v PL/SQL. D li m ngun PL/SQL. To v son tho cc m ngun khi lnh PL/SQL.

Store Program Unit Editor To v son tho cc m ngun khi lnh PL/SQL trong cc Store Program thuc Server. Database Trigger Edditor To v son tho cc m ngun khi lnh PL/SQL trong cc Trigger thuc Server.

13.1.1. Object Navigator


Object Navigator cho php hin th cc i tng trong database. Ta c th to, son tho cc th tc PL/SQL cng nh d li, np cc th vin thng qua Object Navigator. Vi Object Navigator, ta cng c th thc hin sao chp cc th tc, hm thng qua cc thao tc n gin nh copy v paste.

Hnh v 7. Cu trc ca Object Navigator

Cc thnh phn chnh ca Object Navigator bao gm: Navigator drop down litst: Danh sch s xung hin th tn cc th tc Subject indicator: nh v cc i tng cn son tho Type icon: Biu tng cho cc loi
Trang 84

Oracle c bn - SQL v PL/SQL

Object name: Tn cc i tng Find field: Tm kim cc i tng theo tn

13.1.2. Program Unit Editor


L mi trng to, son tho, bin dch v hin th li bin dch cc hm, th tc.

Hnh v 8. Son tho hm, th tc pha Client

Cc thnh phn chnh: Cc nt bm thc hin cng vic: Compile, Apply, Revert, New, Delete, Close v Help Danh sch tn cc hm, th tc khc Ni son tho hm, th tc

13.1.3. Store Program Unit Editor


Cng tng t nh Program Unit Editor, Store Program Unit Editor c s dng cho vic to, son tho cc hm, th tc trn server. Cc chc nng trong Store Program Unit Editor hon ton tng t nh trong Program Unit Editor. Ta ch gi Store Program Unit Editor sau khi thc hin kt ni ti mt database c th no .

13.1.4. Database Trigger Edditor


L mi trng dng to v son tho cc trigger database trn server.

Trang 85

Oracle c bn - SQL v PL/SQL

Hnh v 9. Son tho hm, th tc, trigger pha Server

Trigger database c phn ra lm nhiu loi khc nhau v c thc hin trc hoc sau mi thao tc c th trn tng bng d liu ca database.

13.2.CC HM, TH TC
13.2.1. To hm, th tc trn Client
i vi hm, th tc hay package trn client, ta c th to v bin dch ngay chng. Oracle Builder h tr trnh thng dch cho php kim tra li ca on chng trnh va thc hin.

Hnh v 10. To hm, th tc ti Client

Vic to hm, th tc c thc hin theo ba bc: Khai bo tn hm hay th tc Son tho ni dung ca hm hay thu tc Bin dich hm hay th tc va to v xc nh cc li nu c.

13.2.2. To hm, th tc trn Server


Procedure Builder ch cho php to mi, sa cha v lu li cc thay i i vi cc hm v th tc trn Server, khng h tr vic bin dch v pht hin li.
Trang 86

Oracle c bn - SQL v PL/SQL

Hnh v 11. To hm, th tc ti Server

Ta thc hin vic to hm, th tc trn server theo hai bc: To hm, th tc Son tho v ghi li ni dung ca hm, th tc

13.2.3. D li i vi cc hm, th tc
Vi Procedure Builder, ta c th thc hin chy cc hm, th tc theo tng bc. Qua , ta c th pht hin c cc li xy ra trong chng trnh, nu c. Mn hnh PL/SQL Interpreter cho php ta thc hin iu ny:

Hnh v 12. Mn hnh PL/SQL Interpreter

Cu trc ca mn hnh PL/SQL Interpreter c chia lm ba phn chnh: Phn m ngun hm, th tc Phn iu khin Phn tng tc trc tip vi d liu
Trang 87

Oracle c bn - SQL v PL/SQL

Chng 14. GII THIU CC TH TC, HM V PACKAGE


14.1.TH TC
Mt nhm cc lnh thc hin chc nng no c th c gom li trong mt th tc (procedure) nhm lm tng kh nng x l, kh nng s dng chung, tng tnh bo mt v an ton d liu, tin ch trong pht trin. Th tc c th c lu gi ngay trong database nh mt i tng ca database, sn sng cho vic ti s dng. Th tc lc ny c gi l Store procedure. Vi cc Store procedure, ngay khi lu gi Store procedure, chng c bin dch thnh dng p-code v th c th nng cao kh nng thc hin.

14.1.1. To th tc
Ta c th to th tc trc tip bng dng lnh sau: C php: CREATE [OR REPLACE] PROCEDURE procedure_name [(argument1 [mode1] datatype1, argument2 [mode2] datatype2, ...)] IS | AS BEGIN PL/SQL Block; END; Vi: procedure_name argument mode datatype PL/SQL Block V d: CREATE OR REPLACE PROCEDURE change_sal (p_Percentage IN number, p_Error OUT varchar2, ) IS v_User_exp Exception; BEGIN IF p_Percentage < 0 THEN RAISE v_User_exp; END IF; UPDATE emp SET sal = sal*p_Percentage/100; EXCEPTION
Trang 88

Tn th tc Tn tham s Loi tham s: IN hoc OUT hoc IN OUT, mc nh l IN Kiu d liu ca tham s Ni dung khi lnh SQL v PL/SQL trong th tc

Oracle c bn - SQL v PL/SQL

WHEN v_User_exp THEN p_Error := Li: Phn trm nh hn 0; RETURN; WHEN others THEN p_Error := Li: || SQLERRM; END;

Vi vic to cc th tc thng qua cu lnh, ta c th d dng to cc script cha cc th tc cn thit khi to mi mt database. Mt cch khc, ta c th to mi hay sa i th tc thng qua cng c ca Oracle. Trong chng trc, ta bit cch s dng Procedure Builder to mi th tc.

14.1.2. Hu b th tc
Tng t nh vic to th tc, ta c th hu b th tc thng qua cu lnh SQL. C php: DROP PROCEDURE V d: DROP PROCEDURE change_sal; Tn th tc;

14.1.3. Cc bc lu gi mt th tc
Mt th tc trong Oracle c thc hin theo hai bc chnh sau: 1. Ni dung ca th tc c thit lp v lu gi trong database di dng vn bn (text) 2. Ton b ni dung ca th tc c bin dch ra dng m p-code, tin cho vic thc hin th tc .

Hnh v 13. Cc bc thc hin mt th tc

14.2.HM
Tng t nh th tc, hm (function) cng l nhm cc lnh PL/SQL thc hin chc nng no . Khc vi th tc, cc hm s tr v mt gi tr ngay ti li gi ca n.
Trang 89

Oracle c bn - SQL v PL/SQL

Hm cng c th c lu gi ngay trn database di dng Store procedure.

14.2.1. To hm
Ta c th to hm trc tip bng dng lnh sau: C php: CREATE [OR REPLACE] FUNCTION function_name [(argument1 [mode1] datatype1, argument2 [mode2] datatype2, ...)] RETURN datatype IS | AS BEGIN PL/SQL Block; END; Vi: function_name argument mode datatype PL/SQL Block V d: CREATE OR REPLACE FUNCTION get_sal (p_Emp_id IN number) RETURN varchar2 IS BEGIN SELECT sal FROM emp WHERE emp_id = p_Emp_id; RETURN null; EXCEPTION WHEN others THEN RETURN Li: || SQLERRM; END; Tn hm Tn tham s Loi tham s: IN hoc OUT hoc IN OUT, mc nh l IN Kiu d liu ca tham s Ni dung khi lnh SQL v PL/SQL trong th tc

14.2.2. Thc hin mt hm


Qu trnh lu gi v bin dch mt hm cng tng t nh i vi mt th tc. Qu trnh gi v thc hin mt hm c din ra theo ba bc: 1. Vic gi hm c thc hin ngay khi tn hm trong biu thc c tham chiu ti 2. Mt bin host (host variable) c t ng to ra lu gi gi tr tr v ca hm 3. Thc hin ni dung trong phn thn hm, lu li gi tr

Trang 90

Oracle c bn - SQL v PL/SQL

V d: SQL> VARIABLE v_Sal number; SQL> EXECUTE :v_SAL := get_sal(7934); PL/SQL procedure successfully completed. SQL> PRINT v_Sal; v_Sal 1300

14.2.3. Li ch ca vic s dng hm


Vi vic s dng hm, trong mt s trng hp ta c th thy c cc li im nh sau: Cho php thc hin cc thao tc phc tp (cc php tm kim, so snh phc tp) ngay trong mnh ca cu lnh SQL m nu khng s dng hm ta s khng th no thc hin c Tng tnh c lp ca d liu do vic phn tch v x l d liu c thc hin ngay trn Server thay v tr v d liu trc tip cho ng dng di Client chng tip tc x l. Tng tnh hiu qu ca cu lnh truy vn bng vic gi cc hm ngay trong cu lnh SQL Ta c th s dng hm thao tc trn cc kiu d liu t to. Cho php thc hin ng thi cc cu lnh truy vn

14.2.4. Mt s hn ch khi s dng hm trong cu lnh SQL


Ch cc hm do ngi dng nh ngha c lu trn database mi c th s dng c cho cu lnh SQL. Cc hm do ngi dng nh ngha ch c p dng cho iu kin thc hin trn cc dng d liu (mnh WHERE), khng th p dng cho cc iu kin thc hin trn nhm (mnh GROUP). Tham s s dng trong hm ch c th l loi IN, khng chp nhn gi tr OUT hay gi tr IN OUT. Kiu d liu tr v ca cc hm phi l kiu d liu DATE, NUMBER, NUMBER. Khng cho php hm tr v kiu d liu nh BOOLEAN, RECORD, TABLE. Kiu d liu tr v ny phi tng thch vi cc kiu d liu bn trong Oracle Server.

14.2.5. Hu b hm
Tng t nh vic to hm, ta c th hu b hm thng qua cu lnh SQL. C php: DROP FUNCTION Tn hm; V d: DROP FUNCTION get_sal;

Trang 91

Oracle c bn - SQL v PL/SQL

14.2.6. Hm v th tc
Ta to cc th tc lu gi mt lot cc cc cu lnh phc v cho nhiu ln gi khc nhau. Th tc c th khng c, c mt hoc nhiu tham s. Tuy nhin th tc khng tr li bt k mt kt qu no. Hm cng ging nh th tc, n cng bao gm mt lot cc cu lnh, c th khng c, c mt hoc nhiu tham s. Tuy nhin khc vi th tc, hm bao gi cng tr v mt kt qu. V vy, ta s dng hm trong cc php tnh ton, gn gi tr. Khi , cu lnh thc hin s d dng v sng sa hn.

So snh gia hm v th tc Th tc Thc hin ging nh thc hin cc cu lnh PL/SQL Khng c kiu gi tr tr v C th tr v mt hoc nhiu gi tr (thng qua tham s OUT) Hm C th c gi ging nh mt phn ca biu thc C cha gi tr tr v Tr v mt gi tr

Li ch ca vic s dng hm, th tc Nng cao hiu sut: Trnh vic ti s dng cc cu lnh nhiu ln bi nhiu User khc nhau. Gim thiu thi gian bin dch cu lnh PL/SQL trong pha phn tch cu lnh. Gim thiu s ln gi lnh thc hin trn database, t , lm gim lu lng truyn thng trn mng. Nng cao kh nng bo tr: Ta c th d dng sa ni dung bn trong cc hm, th tc m khng nh hng n vic giao tip ca chng (cc tham s v li gi vn y nguyn). Thay i ni dung ca mt hm, hay th tc c th ng dng c ngay cho nhiu user khc nhau. Tng tnh bo mt v ton vn ca d liu: Vi vic iu khin truy nhp d liu dn tip i vi cc i tng trong database s lm nng cao tnh bo mt ca d liu. Quan h gia cc cu lnh trong hm, th tc lun c m bo.

14.3.PACKAGE
Package l mt tp hp cc kiu d liu, bin lu gi gi tr v cc th tc, hm c cng mt mi lin h vi nhau, c gp chung li. c im ni bt nht ca package l khi mt phn t trong package c gi th ton b ni dung ca package s c np vo trong h thng. Do , vic gi ti cc phn t khc trong package sau ny s khng phi mt thi gian np vo h thng na. T , nng cao tc thc hin lnh ca ton b hm, th tc c trong package.

14.3.1. Cu trc ca package


Mt package c cu trc lm hai phn. Phn m t (specification) nh ngha cc giao tip c th c ca package vi bn ngoi. Phn thn (body) l cc ci t cho cc giao tip c trong phn m t trn.

Trang 92

Oracle c bn - SQL v PL/SQL

Hnh v 14. Cu trc package

Trong cu trc ca package bao gm 05 thnh phn:


1. Public variable (bin cng cng): l bin m cc ng dng bn ngoi c th tham 2. 3. 4. 5.

chiu ti c. Public procedure (th tc cng cng): bao gm cc hm, th tc ca package c th triu gi t cc ng dng bn ngoi. Private procedure (th tc ring phn): l cc hm, th tc c trong package v ch c th c triu gi bi cc hm hay th tc khc trong package m thi. Global variable (bin tng th): l bin c khai bo dng trong ton b package, ng dng bn ngoi tham chiu c ti bin ny. Private variable (bin ring phn): l bin c khai bo trong mt hm, th tc thuc package. N ch c th c tham chiu n trong bn thn hm hay th tc .

14.3.2. To package
Ta c th to package trc tip bng dng lnh sau: C php khai bo phn m t package: CREATE [OR REPLACE] PACKAGE package_name IS | AS public type and cc item declarations subprogram specifications END package_name; Vi: package_name Tn package type and item declarations Phn khai bo cc bin, hng, cursor, ngoi l v kiu s dng trong ton b package Khai bo cc hm, th tc

subprogram specifications PL/SQL C php khai bo phn thn package:

CREATE [OR REPLACE] PACKAGE BODY package_name

Trang 93

Oracle c bn - SQL v PL/SQL

IS | AS private type and item declarations

subprogram bodies END package_name; Vi: package_name type and item declarations

Khai bo cc kiu ch s dng ring trong package Ni dung ca package

subprogram specifications

Tn package Phn khai bo cc bin, hng, cursor, ngoi l v kiu Khai bo cc hm, th tc PL/SQL

V d: -- Phn khai bo ca package CREATE OR REPLACE PACKAGE comm_package IS v_comm number := 10; -- Khai bo bin c gi tr khi to

-- Khai bo th tc giao tip vi bn ngoi PROCEDURE reset_comm (p_comm IN number); END comm_package; -- Phn thn ca package CREATE OR REPLACE PACKAGE IS

BODY

comm_package

-- Hm ring phn ch s dng trong package FUNCTION validate_comm (v_comm IN number) RETURN BOOLEAN IS v_max_comm number; BEGIN SELECT max(comm) INTO v_max_comm FROM emp; IF v_comm > v_max_comm THEN RETURN FALSE; ELSE RETURN TRUE; END IF; END validate_comm; -- Th tc giao tip vi bn ngoi PROCEDURE reset_comm (p_comm IN number) IS
Trang 94

Oracle c bn - SQL v PL/SQL

v_valid BEGIN

BOOLEAN;

v_valid := validate_comm(p_comm); IF v_valid = TRUE THEN v_comm := p_comm; ELSE RAISE_APPLICATION_ERROR(-20210,Invalid END IF: END reset_comm; END comm_package;

comm);

14.3.3. Hu package
Tng t nh vic to package, ta c th hu b hm thng qua cu lnh SQL. C php: -- Hu phn package specification DROP PACKAGE Tn package; -- Hu phn package body DROP PACKAGE BODY Tn package; V d: DROP PACKAGE DROP PACKAGE comm_package; BODY comm_package;

14.3.4. Li ch ca vic s dng package Tng tnh phn


nh cc thnh phn (Modularity) Ta c th ng gi cc thnh phn, cu trc c quan h logic vi nhau trong cng mt module ng vi mt package. Vic k tha gia cc package rt n gin, v c thc hin mt cch trong sng.

n gin trong vic thit k ng dng Tt c cc thng tin cn thit cho vic giao tip u c t trong phn c t ca package (package specification). Ni dung phn ny c th c son tho v bin dch c lp vi phn thn ca package (package body). Do , cc hm hay th tc c gi ti cc thnh phn ca package c th c bin dch tt. Phn thn ca package c th c tip tc pht trin cho n khi hon thnh ng dng.

n du thng tin (hiding information) Package cho php s dng cc thnh phn bn trong di dng public (cng cng) hay private (ring t). Tu theo yu cu thit k, ta c th cho php truy nhp hay n du thng tin. T , c th bo v c tnh ton vn d liu.

Nng cao hiu sut s dng Ngay khi gi mt hm hay th tc bt k trong package ln u tin. Ton b ni dung ca package s c np vo b nh. Do vy, cc hm v th tc con trong package gi n sau ny c th thc hin ngay m khng cn phi np li vo b nh. Vic ny lm gim thiu thao tc truy xut vo ra (I/O access) nng cao tc .
Trang 95

Oracle c bn - SQL v PL/SQL

Thc hin qu ti (overloading) Package cho php thc hin qu ti i vi cc hm v th tc trong n. Theo , cc hm v th tc khc nhau c th c php t trng tn. Vic ny s nng cao tnh mm do ca vic s dng hm, th tc trong package.

14.3.5. Mt s package chun ca Oracle


Th tc DBMS_ALERT DBMS_APPLICATION_INFO DBMS_DDL DBMS_DESCRIBE DBMS_JOB DBMS_LOCK Hm Cung cp cc s kin v cc thng ip ca database Thng tin v cc hot ng hin thi i vi database Bin dch li cc hm, th tc va package. Phn tch cc index, table, cluster,... Tr v cc din gii cho cc tham s ca th tc, hm Ln k hoch thc hin cc on m lnh PL/SQL Cung cp cc hm cho php yu cu, gii phng, iu chnh cc trng thi kho (lock) i vi tng i tng trn database. Gi cc message t Oracle Server ti Oracle*mail Kt xut cc gi tr tr v t cc hm, th tc, trigger,.. Cho php x l gi ng thi cc thng ip Cung cp cc php truy nhp SQL thay v cc cu lnh session Cho php lu gi cc i tng trong vng nh chia s. Cho php s dng lnh SQL ng truy xut database iu khin cc giao dch, ci thin v nng cao hiu qu i vi cc giao dch nh v khng phn tn Phn tch cc i tng trong tng schema. Cho php truy xut ti file ngay vi cu lnh PL/SQL

DBMS_MAIL DBMS_OUTPUT DBMS_PIPE DBMS_SESSION DBMS_SHARED_POOL DBMS_SQL DBMS_TRANSACTION DBMS_UTILITY UTL_FILE

Trang 96

Oracle c bn - SQL v PL/SQL

Chng 15. DATABASE TRIGGER


Database trigger l nhng th tc c thc hin ngm nh ngay khi thc hin lnh SQL nh INSERT, DELETE, UPDATE nhm m bo cc quy tc logic phc tp ca d liu. Thit k cc database trigger tho mn cc yu cu sau: S dng cc database trigger nhm m bo thc hin tt c cc thao tc c lin quan ti lnh can thip d liu c thc hin. Ch s dng database trigger i vi cc thao tc trng tm. Khng s dng database trigger thc hin cc rng buc sn c trong database Oracle. V d: dng database trigger thay th cho cc constrain. S dng database trigger c th gy ri, kh khn cho vic bo tr v pht trin h thng ln. V th, ta ch s dng database trigger khi tht cn thit.

15.1.TO TRIGGER
Khi to database trigger, ta cn lu ti mt s tiu ch nh: Thi gian thc hin: BEFORE, AFTER Hnh ng thc hin: INSERT, UPDATE, DELETE i tng tc ng: bng d liu Loi trigger thc hin: trn dng lnh hay trn cu lnh Mnh iu kin thc hin Ni dung ca trigger

15.1.1. Phn loi trigger


Ta c th phn loi trigger theo thi gian thc hin nh: BEFORE v AFTER. BEFORE trigger: Trigger c kch hot trc khi thc hin cu lnh. Vic ny c th cho php ta loi bt cc php x l khng cn thit, thm ch c th rollback d liu trong trng hp c th gy ra cc ngoi l (exception). Trigger thuc loi ny thng c s dng i vi cc thao tc INSERT hoc UPDATE. AFTER trigger: Cu lnh c thc hin xong th trigger mi c kch hot. Thc hin cc cng vic thng phi lm sau khi thc hin cu lnh. INSTEAD OF trigger: Loi trigger ny cho php ngi s dng c th thay i mt cch trong sut d liu ca mt s view m khng th thc hin thay i trc tip c. Vi INSTEAD OF trigger, ta c th thc hin vi c ba thao tc: insert, update, delete.

Ta cng c th phn loi trigger theo loi cu lnh kch hot nh: INSERT, UPDATE, DELETE. Trong cc trigger thuc mt trong ba loi lnh: INSERT, UPDATE,DELETE. Trigger UPDATE cn phi ch r thm tn ct d liu kch hot trigger mi khi gi tr d liu trong b thay i. Bn trong Trigger c th c cha cc lnh thao tc d liu. Do , cn phi trnh trng hp lp li theo kiu quy. Mt cch khc ta cng c th phn loi trigger theo s ln kch hot. theo s c 02 loi trigger: Trigger mc lnh: Trigger c kch hot mi khi thc hin cu lnh. Trigger mc dng lnh: Trigger c kch nhiu ln ng vi mi dng d liu chu nh hng bi thao tc thc hin lnh.
Trang 97

Oracle c bn - SQL v PL/SQL

Hnh v 15. Th t thc hin trigger

15.1.2. Lnh to trigger


Ta c th to trigger thng qua lnh script. C php lnh to trigger mc cu lnh: CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name BEGIN PL/SQL Block; END;

C php lnh to trigger mc dng d liu: CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name [REFERENCING OLD AS old | NEW AS new] FOR EACH ROW [WHEN condition] BEGIN PL/SQL Block; END; Vi: trigger _name timing event referencing FOR EACH ROW WHEN table_name PL/SQL Block Tn trigger Thi gian kch hot trigger Loi cu lnh kch hot trigger Tn bin thay th cho gi tr trc v sau thay i ca dng d liu ang x l Trigger thuc loi tc ng trn dng d liu Ch ra mt s iu kin rng buc thc hin trigger Tn bng d liu c gn trigger trn Ni dung khi lnh SQL v PL/SQL trong trigger
Trang 98

Oracle c bn - SQL v PL/SQL

V d: CREATE OR REPLACE TRIGER BEFORE INSERT ON emp BEGIN IF TO_CHAR(sysdate,DY) IN (SAT,SUN) OR TO_CHAR(sysdate,HH24) NOT BETWEEN 08 AND 18 THEN RAISE_APPLICATION_ERROR (-20500, Thi gian lm vic khng ph hp); END IF; END; CREATE OR REPLACE TRIGER audit_emp_values AFTER DELETE OR INSERT OR DELETE ON emp FOR EACH ROW BEGIN INSERT INTO audit_emp_values (user_name, timestamp, id, old_last_name, new_last_name, old_title, new_tile, old_salary, new_salary) VALUES (USER, SYSDATE, :old.empno, :old.ename, :new.ename, :old.job, :new.job, :old.sal, :new.sal); END; secure_emp

15.1.3. S dng Procedure builder to trigger


Ta cng c th to database trigger thng qua cng c Procedure builder ca Oracle. Ta ln lt thc hin theo cc bc sau:
1. Kt ni ti database 2. Dch chuyn ti i tng t trigger trong phn Object Navigator 3. Chuyn ti phn trigger ri bm nt New to mi trigger. 4. t cc tu chn v thi gian, kiu,.. cho trigger 5. Son tho ni dung ca trigger 6. Lu gi trigger

Trang 99

Oracle c bn - SQL v PL/SQL

Hnh v 16. To trigger bng cng c Procedure Builder

Hnh v 17. Trigger tc ng trn dng d liu

15.2.QUN L TRIGGER
15.2.1. Phn bit database trigger
Trigger v th tc Trigger Lnh to CREATE TRIGGER Lu gi trong T in d liu di dng m ngun v dng p-code c gi ngm nh Khng cho php dng: COMMIT, ROLLBACK, SAVEPOINT Th tc Lnh to CREATE PROCEDURE Lu gi trong T in d liu di dng m ngun v dng p-code Thc hin theo li gi tng minh Cho php dng: COMMIT, ROLLBACK, SAVEPOINT.

Trang 100

Oracle c bn - SQL v PL/SQL

Database Trigger v Form Trigger Database Trigger c thc hin khi c tc ng ln database do ng dng hoc do chnh cc cng c ca Oracle c kch hot bi cc lnh SQL Phn bit hai loi trigger trn cu lnh v trn dng d liu Tu theo li xy ra, trigger c th gy ra rollback cu lnh Form Trigger c thc hin ch bi cc tc ng ngay trn ng dng c kch bi cc s kin trn ng dng Khng phn bit Tu theo li xy ra, c th rollback ton b giao dch

Database Trigger c kch hot c lp vi cc Form Trigger

15.2.2. Thay i trng thi ca database trigger


Cho php/ khng cho php kch hot mt databse trigger C php: ALTER TRIGGER Vi: trigger_name V d: -- Cho php trigger c hot ng ALTER TRIGGER check_sal ENABLE; Cho php/ khng cho php kch hot tt c cc databse trigger ca mt bng C php: ALTER TABLE Vi: table_name V d: -- Khng cho php cc trigger ng vi bng emp c hot ng ALTER TABLE Bin dch li databse trigger C php: ALTER TRIGGER trigger_name V d: -- Bin dch li trigger check_sal sau khi sa i ni dung ALTER TRIGGER check_sal COMPILE; COMPILE; emp DISABLE ALL TRIGGERS; Tn bng; table_name DISABLE | ENABLE ALL TRIGGERS; Tn trigger; trigger_name DISABLE | ENABLE;

15.2.3. Hu b trigger
S dng cu lnh SQL hu b trigger.
Trang 101

Oracle c bn - SQL v PL/SQL

C php: DROP TRIGGER V d: DROP TRIGGER check_sal; trigger_name;

15.2.4. Lu khi s dng trigger


Cc trng hp kim tra trigger Kim tra trigger ng vi thao tc d liu nh d nh. Kim tra thc hin trigger theo ng nh mnh When. Kim tra nh hng ca trigger i vi cc trigger khc. Kim tra nh hng ca cc trigger khc i vi trigger ang xem xt.

Th t thc hin trigger v cc kim tra rng buc:


1. Thc hin trigger BEFORE STATMENT 2. Lp trn nhiu dng d liu

a. Thc hin trigger BEFORE ROW b. Thc hin cu lnh thao tc d liu v kim tra ton vn d liu trn dng d liu xem xt c. Thc hin trigger AFTER ROW
3. Thc hin cc php kim tra rng buc 4. Thc hin trigger AFTER STATMENT.

Cc quy tc rng buc i vi trigger: 1. Khng c php sa i d liu trong ct d liu c rng buc thuc loi kho chnh (primary key), kho ngoi (foreign key) hay duy nht. 2. Khng cho php c d liu t cc bng ang thao tc.

Trang 102

Oracle c bn - SQL v PL/SQL

PH LC
A - DANH MC CC HNH V
Hnh v 1. Minh ho cc thnh phn logic trong database ... Hnh v 2. M hnh d liu thc hnh... Hnh v 3. Cu lnh ca SQL*Plus ... Hnh v 4. Hn ch d liu tr v ... Hnh v 5. Cu trc hm SQL ... Hnh v 6. Phn loi hm SQL ... Hnh v 7. Cu trc ca Object Navigator... Hnh v 8. Son tho hm, th tc pha Client... Hnh v 9. Son tho hm, th tc, trigger pha Server ... Hnh v 10. To hm, th tc ti Client ... Hnh v 11. To hm, th tc ti Server ... Hnh v 12. Mn hnh PL/SQL Interpreter ... Hnh v 13. Cc bc thc hin mt th tc ... Hnh v 14. Cu trc package ... Hnh v 15. Th t thc hin trigger... Hnh v 16. To trigger bng cng c Procedure Builder ... Hnh v 17. Trigger tc ng trn dng d liu... ...6 ..7 .12 ...17 ...23 .24 ...84 ..85 ...86 .86 ..87 ...87 .89 ..93 ..98 .100 ..100

Trang 103