3.giao trinh sql_va_pl_sql

on

  • 296 views

 

Statistics

Views

Total Views
296
Views on SlideShare
296
Embed Views
0

Actions

Likes
0
Downloads
11
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

3.giao trinh sql_va_pl_sql 3.giao trinh sql_va_pl_sql Document Transcript

  • www.nhipsongcongnghe.net
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLC«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FptHµ Néi, th¸ng 11 n¨m 2002. §µo t¹o Oracle c¬ b¶n Gi¸o tr×nh SQL vµ PL/SQL§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 2
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLMôc lôcMôc lôc .................................................................................................................................................31 Giíi thiÖu.......................................................................................................................................6 1.1 Môc tiªu kho¸ häc ..............................................................................................................................6 1.2 Khëi ®éng vµ tho¸t khái Oracle.........................................................................................................6 1.2.1 T¹i Server (Window NT) .........................................................................................6 1.2.2 T¹i Client (Window 9x) ............................................................................................6 1.3 Giíi thiÖu ng«n ng÷ SQL ...................................................................................................................7 1.3.1 LÞch sö ph¸t triÓn cña ng«n ng÷ SQL .....................................................................7 1.3.2 ChuÈn SQL .............................................................................................................7 1.4 C¸c kh¸i niÖm trong CSDL.................................................................................................................7 1.5 Danh s¸ch rót gän c¸c ®èi t−îng CSDL ...........................................................................................8 1.6 C¸c lÖnh SQL ......................................................................................................................................8 1.7 Giíi thiÖu vÒ vÝ dô thùc hµnh.............................................................................................................9 1.7.1 M« h×nh quan hÖ d÷ liÖu..........................................................................................9 1.7.2 M« t¶ d÷ liÖu............................................................................................................92 LÖnh truy vÊn c¬ b¶n ...........................................................................................................10 2.1 LÖnh truy vÊn c¬ b¶n........................................................................................................................10 2.2 C¸c thµnh phÇn kh¸c cña mÖnh ®Ò SELECT..................................................................................10 2.3 Gi¸ trÞ Null..........................................................................................................................................11 2.4 Läc d÷ liÖu tõ c¸c row cã cïng gi¸ trÞ.............................................................................................11 2.5 HiÓn thÞ cÊu tróc b¶ng ......................................................................................................................12 2.6 C¸c lÖnh cña c«ng cô SQL*Plus......................................................................................................12 2.6.1 C¸c lÖnh so¹n th¶o ...............................................................................................12 2.6.2 C¸c lÖnh vÒ file......................................................................................................13 2.6.3 C¸c lÖnh vÒ column...............................................................................................13 2.7 Bµi tËp................................................................................................................................................143 Truy vÊn d÷ liÖu cã ®iÒu kiÖn ............................................................................................16 3.1 MÖnh ®Ò ORDER BY .........................................................................................................................16 3.2 MÖnh ®Ò WHERE...............................................................................................................................16 3.3 C¸c to¸n tö ........................................................................................................................................17 3.4 Bµi tËp................................................................................................................................................194 C¸c hµm ¸p dông cho 1 dßng d÷ liÖu..............................................................................20 4.1 C¸c hµm sè........................................................................................................................................20 4.2 C¸c hµm ký tù ...................................................................................................................................22 4.3 C¸c hµm ngµy ...................................................................................................................................26 4.4 C¸c hµm chuyÓn ®æi kiÓu.................................................................................................................28 4.5 Bµi tËp................................................................................................................................................295 BiÕn runtime..............................................................................................................................31 5.1 Bµi tËp................................................................................................................................................326 C¸c hµm nhãm ¸p dông cho lín h¬n hoÆc b»ng 1 dßng d÷ liÖu ........................32 6.1 C¸c hµm t¸c ®éng trªn nhãm ..........................................................................................................32 6.2 MÖnh ®Ò GROUP BY .........................................................................................................................34 6.3 Bµi tËp................................................................................................................................................357 HiÓn thÞ néi dung d÷ liÖu tõ nhiÒu b¶ng ........................................................................35 7.1 Mèi liªn kÕt t−¬ng ®−¬ng .................................................................................................................35§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 3
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL 7.2 Mèi liªn kÕt kh«ng t−¬ng ®−¬ng......................................................................................................35 7.3 Mèi liªn kÕt céng...............................................................................................................................36 7.4 Liªn kÕt cña b¶ng víi chÝnh nã .......................................................................................................36 7.5 C¸c to¸n tö tËp hîp ..........................................................................................................................36 7.6 Bµi tËp................................................................................................................................................378 C¸c lÖnh truy vÊn lång nhau...........................................................................................39 8.1 C©u lÖnh SELECT lång nhau. ..........................................................................................................39 8.2 Bµi tËp................................................................................................................................................409 CÊu tróc h×nh c©y...................................................................................................................40 9.1 CÊu tróc h×nh c©y trong 1 table .......................................................................................................40 9.2 Kü thuËt thùc hiÖn ............................................................................................................................41 9.3 Bµi tËp................................................................................................................................................4210 Tæng kÕt vÒ lÖnh select .....................................................................................................4411 T¹o table ...................................................................................................................................44 11.1 LÖnh t¹o b¶ng ...................................................................................................................................44 11.2 C¸c quy t¾c ®Æt tªn object ...............................................................................................................46 11.3 C¸c quy t¾c khi tham chiÕu ®Õn object...........................................................................................47 11.4 KiÓu d÷ liÖu vµ ®iÒu kiÖn ..................................................................................................................47 11.4.1 CHAR ....................................................................................................................47 11.4.2 VARCHAR2...........................................................................................................48 11.4.3 VARCHAR.............................................................................................................48 11.4.4 NUMBER...............................................................................................................48 11.4.5 FLOAT...................................................................................................................48 11.4.6 LONG ....................................................................................................................49 11.4.7 DATE.....................................................................................................................49 11.4.8 RAW vµ LONG RAW ............................................................................................50 11.4.9 ROWID ..................................................................................................................50 11.4.10 MLSLABEL............................................................................................................50 11.4.11 ChuyÓn ®æi kiÓu ....................................................................................................50 11.5 Constraint..........................................................................................................................................51 11.6 Bµi tËp................................................................................................................................................5212 c¸c lÖnh DDL kh¸c vµ d÷ liÖu trong tõ ®iÓn d÷ liÖu...............................................52 12.1 ChØnh söa cÊu tróc table ..................................................................................................................52 12.2 C¸c lÖnh DDL kh¸c ...........................................................................................................................53 12.2.1 Xãa table ...............................................................................................................53 12.2.2 Gi¶i thÝch b¶ng ......................................................................................................53 12.2.3 Thay ®æi tªn object................................................................................................53 12.2.4 Xãa d÷ liÖu cña table.............................................................................................53 12.3 D÷ liÖu trong tõ ®iÓn d÷ liÖu ............................................................................................................54 12.4 Bµi tËp................................................................................................................................................5413 C¸c lÖnh Thao t¸c d÷ liÖu kh¸c ......................................................................................55 13.1 ChÌn mét row vµo table ...................................................................................................................55 13.2 ChØnh söa d÷ liÖu..............................................................................................................................55 13.3 Xãa dßng ...........................................................................................................................................55 13.4 Lçi rµng buéc d÷ liÖu .......................................................................................................................56 13.5 LÖnh ®iÒu khiÓn giao dÞch................................................................................................................56 13.6 Bµi tËp................................................................................................................................................5714 Sequence vµ index..................................................................................................................57§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 4
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL 14.1 Sequence...........................................................................................................................................57 14.1.1 T¹o Sequence.......................................................................................................57 14.1.2 Xo¸ vµ söa sequence ...........................................................................................58 14.2 Index ..................................................................................................................................................58 14.3 Bµi tËp................................................................................................................................................5915 T¹o view ......................................................................................................................................59 15.1 View....................................................................................................................................................59 15.2 Bµi tËp................................................................................................................................................6116 QuyÒn vµ b¶o mËt ...................................................................................................................61 16.1 QuyÒn - PRIVILEGE ..........................................................................................................................61 16.2 ROLE..................................................................................................................................................62 16.3 Synonym............................................................................................................................................6317 tæng quan vÒ pl/sql vµ procedure builder...............................................................63 17.1 Có ph¸p lÖnh PL/SQL .......................................................................................................................63 17.2 PL/SQL block ....................................................................................................................................63 17.3 Giíi thiÖu Procedure builder............................................................................................................6418 có ph¸p lËp tr×nh ...................................................................................................................66 18.1 IF ........................................................................................................................................................66 18.2 LOOP vµ EXIT....................................................................................................................................66 18.3 FOR ....................................................................................................................................................67 18.4 WHILE ................................................................................................................................................67 18.5 GOTO .................................................................................................................................................6719 cursor ........................................................................................................................................68 19.1 §Þnh nghÜa .........................................................................................................................................68 19.2 KiÓu d÷ liÖu Table vµ Record...........................................................................................................69 19.3 Sao kiÓu d÷ liÖu ................................................................................................................................70 19.4 C©u lÖnh SELECT... INTO... trong PL/SQL......................................................................................70 19.5 Bµi tËp................................................................................................................................................7020 procedure vµ funtion..........................................................................................................71 20.1 Procedure ..........................................................................................................................................71 20.2 Function.............................................................................................................................................72 20.3 Bµi tËp................................................................................................................................................7321 pakage.........................................................................................................................................73 21.1 Package .............................................................................................................................................7322 database trigger ..................................................................................................................74 22.1 Database Trigger...............................................................................................................................74 22.2 Bµi tËp................................................................................................................................................7523 error handing .........................................................................................................................76 23.1 Bµi tËp................................................................................................................................................78§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 5
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL1 Giíi thiÖu1.1 Môc tiªu kho¸ häcKÕt thóc kho¸ häc häc viªn ph¶i n¾m ®−îc• HiÓu ®−îc ph−¬ng ph¸p, c¸c thµnh phÇn, thuËt ng÷ vµ thao t¸c trong CSDL quan hÖ• T¹o ®−îc c¸c cÊu tróc d÷ liÖu nh− table, view dïng SQL• Ghi, ®äc, vµ cËp nhËt d÷ liÖu trong CSDL• X©y dùng c¸c PL/SQL block dïng Procedure Builder1.2 Khëi ®éng vµ tho¸t khái Oracle1.2.1 T¹i Server (Window NT)SQLDBA cung cÊp c¸c dÞch vô qu¶n trÞ hÖ thèng, nh−: t¹o lËp CSDL, më - ®ãng CSDL, t¹o vµ qu¶n lý c¸cUSER ... C¸c b−íc ®Ó khëi ®éng t¹i Server nh− sau:• Khëi ®éng m¸y chñ• BËt dÞch vô OracleServiceXXX (trong ®ã XXX lµ tªn cña CSDL) b»ng c¸ch nhÊn vµo Start -> Program - > Service -> OracleServiceXXX -> NhÊn chuét ph¶i -> NhÊn Start. Chó ý chØ bËt dÞch vô nµy khi ng−êi cµi ®Æt kh«ng ®Ó chÕ ®é tù ®éng hay khi dÞch vô nµy ch−a ®−îc bËt.• BËt dÞch vô OracleXXXTNSLÝstener (trong ®ã XXX lµ tªn cña Database Home) b»ng c¸ch nhÊn vµo Start -> Program -> Service -> OracleXXXTNSLÝstener -> NhÊn chuét ph¶i -> NhÊn Start. Chó ý chØ bËt dÞch vô nµy khi ng−êi cµi ®Æt kh«ng ®Ó chÕ ®é tù ®éng hay khi dÞch vô nµy ch−a ®−îc bËt.• Khi bËt xong CSDL ®· s½n sµng ®Ó lµm viÖc§Ó ®ãng CSDL cÇn lµm theo c¸c b−íc ng−îc l¹i:• T¾t dÞch vô OracleXXXTNSLÝstener (trong ®ã XXX lµ tªn cña Database Home) b»ng c¸ch nhÊn vµo Start -> Program -> Service -> OracleXXXTNSLÝstener -> NhÊn chuét ph¶i -> NhÊn Stop.• T¾t dÞch vô OracleServiceXXX (trong ®ã XXX lµ tªn cña CSDL) b»ng c¸ch nhÊn vµo Start -> Program - > Service -> OracleServiceXXX -> NhÊn chuét ph¶i -> NhÊn Stop.• Shutdown m¸y chñ.1.2.2 T¹i Client (Window 9x)C¸c øng dông cña oracle ch¹y trong m«i tr−êng Windows víi giao diÖn graphic, c¸c øng dông th−êng dïngcã SQL*Plus, Oracle Form, Oracle Report, Oracle Designer ... ViÖc ch¹y c¸c øng dông nµy hoµn toµn gièngnh− viÖc ch¹y c¸c øng dông th«ng th−êng trong m«i tr−êng windows.§Ó lµm viÖc víi c¸c øng dông truy cËp CSDL Oracle, ng−êi sö dông (NSD) ph¶i connect vµo CSDL. Cã haic¸ch ®Ó connect.Connect NSD/password, vÝ dô NSD tªn Scott cã password lµ tiger th×Connect Scott/tigerPh¸t lÖnh connect víi tªn NSD, khi ®ã Oracle sÏ hái passwordConnect ScottEnter password: *****§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 6
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLNSD cã thÓ lµm viÖc trong ph¹m vi cho phÐp cña m×nh mµ Oracle gäi lµ "khung c¶nh" (Schema) cña NSD.Mçi khung c¶nh chøa nhiÒu ®èi t−îng c¸c lo¹i, NSD chØ cã thÓ t¸c ®éng lªn c¸c ®èi t−îng trong khung c¶nhcña m×nh.Trong c¸c øng dông ®Òu cã chøc n¨ng tho¸t vµ tù ®éng disconnect.§Ó thùc hµnh phÇn SQL vµ PL/SQL gäi øng dông SQL* Plus.1.3 Giíi thiÖu ng«n ng÷ SQL1.3.1 LÞch sö ph¸t triÓn cña ng«n ng÷ SQLM« h×nh c¬ së d÷ liÖu (CSDL) quan hÖ do E.F Codd ®−a ra vµo ®Çu thËp kû 70, tõ ®ã ®Õn nay nã liªn tôcph¸t triÓn trë thµnh m« h×nh CSDL phæ biÕn bËc nhÊt (RDBMS). M« h×nh quan hÖ gåm c¸c thµnh phÇn sau:• TËp hîp c¸c ®èi t−îng vµ/hoÆc c¸c mèi quan hÖ• TËp hîp c¸c xö lý t¸c ®éng tíi c¸c quan hÖ• Rµng buéc d÷ liÖu ®¶m b¶o tÝnh chÝnh x¸c vµ nhÊt qu¸n.SQL (Structured Query Language, ®äc lµ "sequel") lµ tËp lÖnh truy xuÊt CSDL quan hÖ. Ng«n ng÷ SQL ®−îcIBM sö dông ®Çu tiªn trong hÖ qu¶n trÞ CSDL System R vµo gi÷a nh÷ng n¨m 70, hÖ ng«n ng÷ SQL ®Çu tiªn(SEQUEL2) ®−îc IBM c«ng bè vµo th¸ng 11 n¨m 1976. N¨m 1979, tËp ®oµn ORACLE giíi thiÖu th−¬ngphÈm ®Çu tiªn cña SQL, SQL còng ®−îc cµi ®Æt trong c¸c hÖ qu¶n trÞ CSDL nh− DB2 cña IBM vµ SQL/DS.Ngµy nay, SQL ®−îc sö dông réng r·i vµ ®uîc xem lµ ng«n ng÷ chuÈn ®Ó truy cËp CSDL quan hÖ.1.3.2 ChuÈn SQLN¨m 1989, viÖn tiªu chuÈn quèc gia Hoa kú (ANSI) c«ng nhËn SQL lµ ng«n ng÷ chuÈn ®Ó truy cËp CSDLquan hÖ trong v¨n b¶n ANSI SQL89.N¨m 1989, tæ chøc tiªu chuÈn quèc tÕ (ISO) c«ng nhËn SQL ng«n ng÷ chuÈn ®Ó truy cËp CSDL quan hÖtrong v¨n b¶n ISO 9075-1989.TÊt c¶ c¸c hÖ qu¶n trÞ CSDL lín trªn thÕ giíi cho phÐp truy cËp b»ng SQL vµ hÇu hÕt theo chuÈn ANSI.1.4 C¸c kh¸i niÖm trong CSDLTable lµ cÊu tróc l−u tr÷ c¬ b¶n nhÊt trong CSDL quan hÖ (RDBMS), nã bao gåm 1 hoÆc nhiÒu column vµ 0 hoÆc nhiÒu row.Row lµ tæ hîp nh÷ng gi¸ trÞ cña Column trong b¶ng. Mét row cßn cã thÓ ®−îc gäi lµ 1 record.Column hiÓn thÞ mét lo¹i d÷ liÖu trong b¶ng, vÝ dô tªn phßng ban trong b¶ng phßng ban. Ng−êi ta thÓ hiÖn nã th«ng qua tªn column vµ gi÷ sè liÖu d−íi c¸c kiÓu vµ kÝch cì nhÊt ®Þnh.Field lµ giao cña column vµ row. Field chÝnh lµ n¬i chøa d÷ liÖu. NÕu kh«ng cã d÷ liÖu trong field ng−êi ta nãi field cã gia trÞ lµ null.Primary Key lµ mét column hoÆc mét tËp c¸c column x¸c ®Þnh tÝnh duy nhÊt cña c¸c row ë trong b¶ng. VÝ dô m· phßng ban. Primary Key nhÊt thiÕt ph¶i cã sè liÖu.Foreign Key lµ mét column hoÆc mét tËp c¸c column tham chiÕu tíi chÝnh b¶ng ®ã hoÆc mét b¶ng kh¸c. Foreign Key x¸c ®Þnh mèi quan hÖ gi÷a c¸c b¶ng.Constraint lµ c¸c rµng buéc d÷ liÖu, vÝ dô Foreign Key, Primary Key...§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 7
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLVÝ dô: EMP DEPT EMPNO ENAME DEPTNO EMP DEPT DEPTNO DNAME 7369 SMITH 20 10 ACCOUNTING Row 7499 ALLEN 30 20 RESEARCH 7521 WARD 30 30 SALES 7566 JONES 20 40 OPERATIONS 7654 MARTIN 30 7698 BLAKE 30 Foreign key 7782 CLARK 10 Primary key Column1.5 Danh s¸ch rót gän c¸c ®èi t−îng CSDLTable lµ cÊu tróc l−u tr÷ c¬ b¶n nhÊt trong CSDL quan hÖ (RDBMS), gåm row vµ columnView lµ cÊu tróc logic hiÓn thÞ d÷ liÖu tõ 1 hoÆc nhiÒu b¶ngSequence kÕt sinh gi¸ trÞ cho c¸c primary keyIndex t¨ng tÝnh thùc thi cña c¸u truy vÊnSynonym tªn t−¬ng ®−¬ng cña ®èi t−îngProgram unit gåm Procedure, function, package...1.6 C¸c lÖnh SQLLÖnh M« t¶SELECT Lµ lÖnh th«ng dông nhÊt, dïng ®Ó lÊy, xem d÷ liÖu trong CSDL.INSERT Lµ 3 lÖnh dïng ®Ó nhËp thªm nh÷ng row míi, thay ®æi néi dung d÷ liÖu trªn c¸c rowUPDATE hay xo¸ c¸c row trong table. Nh÷ng lÖnh nµy ®−îc gäi lµ c¸c lÖnh thao t¸c d÷ liÖuDELETE DML (Data Manipulation Language)CREATE Lµ 3 lÖnh dïng ®Ó thiÕt lËp, thay ®æi hay xo¸ bá cÊu tróc d÷ liÖu nh− lµ table, view,ALTER index. Nh÷ng lÖnh nµy ®−îc gäi lµ c¸c lÖnh ®Þnh nghÜa d÷ liÖu DDL (Data DefinitionDROP Language)RENAMETRUNCATECOMMIT Qu¶n lý viÖc thay ®æi d÷ liÖu b»ng c¸c lÖnh DML. ViÖc thay ®æi d÷ liÖu cã thÓ ®−îcROLLBACK nhãm l¹i thµnh c¸c transaction.SAVE POINTGRANT 2 lÖnh nµy dïng ®Ó g¸n hoÆc huû c¸c quyÒn truy nhËp vµo CSDL Oracle vµ c¸c cÊuREVOKE tróc bªn trong nã. Nh÷ng lÖnh nµy ®−îc gäi lµ c¸c lÖnh ®iÒu khiÓn d÷ liÖu DCL (Data§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 8
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL Control Language)1.7 Giíi thiÖu vÒ vÝ dô thùc hµnh1.7.1 M« h×nh quan hÖ d÷ liÖu DEPT EMP SALGRADE DUMMY BONUS1.7.2 M« t¶ d÷ liÖu Tªn KiÓu Kho¸ Gi¶i thÝch DEPT DEPTNO NUMBER(2) NOT NULL PK M· phßng ban DNAME CHAR(14) Tªn phßng ban LOC CHAR(13) §Þa chØ SALGRADE GRADE NUMBER PK Møc l¬ng LOSAL NUMBER Gi¸ trÞ thÊp HISAL NUMBER Gi¸ trÞ cao EMP EMPNO NUMBER(4) NOT NULL, PK M· nh©n viªn ENAME CHAR(10), Tªn nh©n viªn JOB CHAR(9), NghÒ nghiÖp MGR NUMBER(4) FK (EMP.EMPNO) M· ng−êi qu¶n lý HIREDATE DATE Ngµy gia nhËp c«ng ty SAL NUMBER(7,2) L−¬ng COMM NUMBER(7,2) Th−ëng DEPTNO NUMBER(2) NOT NULL, FK (DEPT.DEPTNO) M· phßng ban§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 9
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL2 LÖnh truy vÊn c¬ b¶n2.1 LÖnh truy vÊn c¬ b¶n SELECT [DISTINCT ] {*, column [alias],...} FROM table;• SELECT tr¶ lêi c©u hái lÊy d÷ liÖu nµo? (column, biÓu thøc...), trong mÖnh ®Ò SELECT cÇn cã Ýt nhÊt 1 column.• FROM tr¶ lêi c©u hái lÊy d÷ liÖu ë ®Çu? (table, view...)• DISTINCT chØ ®Þnh hiÓn thÞ 1 lÇn c¸c d÷ liÖu trïng nhau.• * thay cho viÖc chØ tªn tÊt c¶ c¸c column• alias ®−a ra nh·n cña column hiÓn thÞ d÷ liÖu.Vd: SELECT * FROM emp; SELECT empno, ename, deptno, mgr FROM emp; SELECT DISTINCT job nghenghiep FROM emp;2.2 C¸c thµnh phÇn kh¸c cña mÖnh ®Ò SELECTTrong mÖnh ®Ò SELECT cßn cã thÓ ®−a vµo c¸c thµnh phÇn kh¸c:• BiÓu thøc to¸n häc• Column alias• C¸c column ®−îc ghÐp chuçi• LiteralBiÓu thøc to¸n häcTrong mÖnh ®Ò SELECT biÓu thøc to¸n häc cã thÓ c¸c gi¸ trÞ (column hoÆc hµng sè), c¸c to¸n tö, c¸c hµm.C¸c to¸n tö ®−îc dïng lµ (+), (-), (*), (/). §é −u tiªn cña c¸c to¸n tö gièng trong phÇn sè häc. Vd: SELECT ename, sal *12, comm FROM emp; SELECT ename, (sal+250)*12 FROM emp;Column aliasTrong mÖnh ®Ò SELECT, column alias lµ phÇn nh·n hiÓn thÞ cña column khi lÊy sè liÖu ra. Trong columnalias kh«ng ®−îc cã dÊu c¸ch vµ viÕt c¸ch sau tªn column mét dÊu c¸ch. Column alias ®−îc chÊp nhËn cãdÊu c¸ch khi ®−îc ®Æt trong dÊu nh¸y kÐp (“ “).Vd: (ANUAL chÝnh lµ column alias) SELECT ename, SAL*12 ANUAL, comm FROM emp;C¸c column ®−îc ghÐp chuçiTo¸n tö ghÐp chuçi (||) cho phÐp c¸c column ®−îc nèi víi nhau thµnh d¹ng chuçi. Cã thÓ cã nhiÒu to¸n töghÐp chuçi trong cïng mét column alias. Vd: SELECT empno||ename EMPLOYEE FROM emp; SELECT ename || co luong la || (sal+250)*12 as "mieu ta" FROM emp; Chuçi ®Æt trong nh¸y ®¬n, bÝ danh ®Æt trong nh¸y kÐp§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 10
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLLiteralTrong mÖnh ®Ò SELECT, literal lµ bÊt kú ký tù nµo, biÓu thøc, hay sè nµp mµ kh«ng ph¶i lµ column hoÆccolumn alias. Vd: SELECT empno||ename EMPLOYEE, ‘WORK IN DEPARTMENT’, deptno FROM emp;2.3 Gi¸ trÞ NullCét cã gi¸ trÞ rçng (NULL) lµ cét ch−a ®−îc g¸n gi¸ trÞ, nãi c¸ch kh¸c nã ch−a ®−îc khëi t¹o gi¸ trÞ. C¸c cétvíi bÊt cø kiÓu d÷ liÖu nµo còng cã thÓ cã trÞ NULL, trõ khi ®−îc nã lµ khãa hay cã rµng buéc toµn vÑn NOTNULL. Trong biÓu thøc cã bÊt kú gi¸ trÞ NULL nµo kÕt qu¶ còng lµ NULL. Vd: SELECT ename, sal*12 + comm ANUAL_SAL FROM emp;NULL trong c¸c hµm cña SQL- Trong c¸c hµm lµm viÖc víi tõng cét hay hµm v« h−íng (scalar function)C¸c hµm lo¹i nµy tr¶ vÒ trÞ null khi cã tham sè null, trõ hµm NVL vµ TRANSLATE cã thÓ tr¶ vÒ gi¸ trÞ thùc.Có ph¸p cña hµm NVL NVL (DATECOLUMN,’01-01-2001’) NVL(NUMBERCOLUMN, 9) NVL(CHARCOLUMN,’STRING’)VÝ dô: NVL(comm,0) tr¶ vÒ trÞ 0 khi comm lµ null SELECT ename, sal*12 + NVL(comm,0) ANUAL_SAL FROM emp;- Trong c¸c hµm lµm viÖc víi nhãm c¸c cét (group function)HÇu hÕt c¸c hµm lµm viÖc trªn nhãm bá qua trÞ null, vÝ dô nh− khi sö dông hµm AVG ®Ó tÝnh trung b×nh chomét cét cã c¸c gi¸ trÞ 1000, null, null, null, 2000 khi ®ã trung b×nh ®−îc tÝnh lµ (1000+2000)/2=1500, nh− vËytrÞ null bÞ bá qua chø kh«ng ph¶i xem lµ trÞ 0.NULL trong c¸c biÓu thøc so s¸nh, ®iÒu kiÖn§Ó kiÓm tra cã ph¶i null hay kh«ng dïng c¸c to¸n tö IS NULL hoÆc IS NOT NULL. NÕu trong biÓu thøc sos¸nh cã trÞ null tham gia vµ kÕt qu¶ cña biÓu thøc phô thuéc vµo trÞ null th× kÕt qu¶ lµ kh«ng x¸c ®Þnh, tuynhiªn trong biÓu thøc DECODE, hai gi¸ trÞ null ®−îc xem lµ b»ng nhau trong phÐp so s¸nh.ORACLE xem c¸c biÓu thøc víi kÕt qu¶ kh«ng x¸c ®Þnh t−¬ng ®−¬ng víi FALSE, vÝ dô comm = NULL cã kÕtqu¶ kh«ng x¸c ®Þnh vµ do ®ã biÓu thøc so s¸nh xem nh− cho kÕt qu¶ FALSE. Trong c©u lÖnh sau kh«ng cãmÉu tin nµo ®−îc chänSELECT * FROM emp WHERE comm=NULL;NÕu muèn chän c¸c nh©n viªn cã comm lµ NULL th× ph¶i dïng to¸n tö IS NULLSELECT * FROM emp WHERE comm IS NULL;2.4 Läc d÷ liÖu tõ c¸c row cã cïng gi¸ trÞMét c©u lÖnh truy vÊn cã thÓ tr¶ vÒ c¸c row cã cïng gÝa trÞ. Vd: SELECT JOB FROM EMP; SELECT DEPTNO FROM EMP; SELECT JOB, DEPTNO FROM EMP;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 11
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL§Ó läc lÊy mét gi¸ trÞ duy nhÊt ng−êi ta dïng mÖnh ®Ò DISTINCT. MÖnh ®Ò nµy ph¶i ®−îc ®Æt tr−íc tÊt c¶c¸c column, sau mÖnh ®Ò SELECT. Vd: SELECT DISTINCT JOB FROM EMP; SELECT DISTINCT DEPTNO FROM EMP; SELECT DISTINCT JOB, DEPTNO FROM EMP;2.5 HiÓn thÞ cÊu tróc b¶ngCó ph¸p DESC[RIBE] table_name(lÖnh nµy chØ ch¹y ®−îc trªn sqlplus, kh«ng ch¹y ®−îc trªn PL/SQL Develop)VÝ dô: DESC emp; Name Null? Type ------------------------------- -------- ---- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) JOB VARCHAR2(9) MGR NUMBER(4) HIREDATE DATE SAL NUMBER(7,2) COMM NUMBER(7,2) DEPTNO NUMBER(2)KiÓu d÷ liÖu NOT NULL nghÜa lµ column nhÊt ®Þnh ph¶i cã gi¸ trÞ.2.6 C¸c lÖnh cña c«ng cô SQL*Plus2.6.1 C¸c lÖnh so¹n th¶o LÖnh M« t¶ A[PPEND] text §−a thªm ®o¹n text vµo dßng hiÖn t¹i C[HANGE] /old/new ChuyÓn ®o¹n text cò thµnh ®o¹n text míi trong dßng hiÖn t¹i C[HANGE] /text/ Xo¸ ®o¹n text trong dßng hiÖn t¹i CL[EAR] BUFF[ER] Xo¸ tÊt c¶ c¸c dßng trong SQL buffer DEL Xo¸ dßng hiÖn t¹i DEL n Xo¸ dßng n DEL m n Xo¸ dßng tõ m ®Õn n I[NPUT] Thªm mét sè dßng nhÊt ®Þnh I[NPUT] text Thªm dßng cã chøa text L[IST] LiÖt kª toµn bé c¸c dßng trong SQL buffer L[IST] n LiÖt kª dßng n L[IST] m n LiÖt kª dßng m ®Õn n§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 12
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL R[UN] HiÓn thÞ vµ ch¹y lÖnh trong buffer N Nhµy ®Õn dßng n N text Thay dßng n bëi ®o¹n text 0 text ChÌn 1 dßng tr−íc dßng 12.6.2 C¸c lÖnh vÒ file LÖnh M« t¶ SAVE filename [.ext] [REP[LACE]|APP[END]] Ghi néi dung bufer thµnh file. APPEND ®Ó ghi thªm vµo file. REPLACE ®Ó chÌn lªn néi dung file cò. GET filename [.ext] Ghi néi dung file vµo buffer. MÆc ®Þnh phÇn ®u«i lµ .sql STA[RT] filename [.ext] Ch¹y c¸c lÖnh trong file @ filename [.ext] Gièng lÖnh Start ED[IT] So¹n th¶o néi dung bufffer cã tªn lµ afiedt.buf §Ó ch¹y néi dung buffer dïng lÖnh / ED[IT] filename [.ext ] So¹n th¶o néi dung file SPO[OL] filename [.ext ] [OFF|OUT] CÊt kÕt qu¶ hiÓn thÞ trªn mµn h×nh ra file. Vd: SPOOL result.sql .... SPOOL OFF EXIT Tho¸t khái SQL*Plus2.6.3 C¸c lÖnh vÒ columnCó ph¸p COLUMN [{column | alias} [option]]LÖnh M« t¶CLE[AR] Xo¸ ®Þnh d¹ng cña columnFOR[MAT] format ChuyÓn ®Þnh d¹ng cña cét d÷ liÖuHEA[DING] text §Æt nh·n co columnJUS[TIFY] align C¸n tr¸i “ left , ph¶i - right, gi÷a - center cho nh·nNOPRI[NT] Èn columnNUL[L] text HiÓn thÞ text nÕu gi¸ trÞ cña column lµ NULLPRI[NT} HiÓn thÞ column§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 13
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLTRU[NCATED] Xo¸ chuçi t¹i cuèi dßng ®Çu tiªn khi hiÓn thÞWRA[PPED] Phñ cuèi chuçi cña dßng tiÕp theoWOR[D_WAPPED] Gièng WAP nh−ng tõ kh«ng bÞ c¾tL−u ý: c¸c ®Þnh d¹ng hiÓn thÞ nµy ®−îc l−u vµo bé nhí vµ ¸p dông cho mäi cét cã tªn nh− vËy, dï chóng ëtrong b¶ng nµoVd: ChØnh ®Þnh d¹ng vµ nh·n cña column COLUMN ename HEADING ‘Employee|Name’ FORMAT A15 COLUMN sal JUSTIFY LEFT FORMAT $ 99,990.00 COLUMN hiredate FORMAT A9 NULL ‘ Not hired’Vd: HiÓn thÞ ®Þnh d¹ng hiÖn t¹i cña column COLUMN COLUMN enameVd: Xo¸ ®Þnh d¹ng hiÖn t¹i cña column COLUMN ename CLEAR CLEAR COLUMNC¸c lo¹i ®Þnh d¹ng §Þnh M« t¶ VÝ dô KÕt qu¶ d¹ng An HiÓn thÞ dµi nhÊt n ký tù dïng cho c¸c column d¹ng ký tù hoÆc d¹ng ngµy 9 HiÓn thÞ sè, kh«ng bao gåm sè 0 999999 1234 0 HiÓn thÞ c¶ sè 0 099999 01234 $ HiÓn thi $ $9999 $1234 L HiÓn thÞ ký tù L L9999 L1234 . HiÓn thÞ dÊu thËp ph©n 9999.99 1234.00 , HiÓn thÞ dÊu ph©n chia hµng ngh×n 9,999 1,2342.7 Bµi tËp1. Chän toµn bé th«ng tin trong b¶ng SALGRADE GRADE LOSAL HISAL ---------- ---------- ---------- 1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 99992. Chän toµn bé th«ng tin trong b¶ng EMP EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ------ ---------- --------- ----- --------- ----- ------ ---------- 7839 KING PRESIDENT 17-11-1981 5000 10 7698 BLAKE MANAGER 7839 01-05-1981 2850 30 7782 CLARK MANAGER 7839 09-06-1981 2450 10 7566 JONES MANAGER 7839 02-04-1981 2975 20§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 14
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL 7654 MARTIN SALESMAN 7698 28-09-1981 1250 1400 30 7499 ALLEN SALESMAN 7698 20-02-1981 1600 300 30 7844 TURNER SALESMAN 7698 08-09-1981 1500 0 30 7900 JAMES CLERK 7698 03-12-1981 950 30 7521 WARD SALESMAN 7698 22-02-1981 1250 500 30 7902 FORD ANALYST 7566 03-12-1981 3000 20 7369 SMITH CLERK 7902 17-12-1980 800 20 7788 SCOTT ANALYST 7566 09-12-1982 3000 20 7876 ADAMS CLERK 7788 12-01-1983 1100 20 7934 MILLER CLERK 7782 23-01-1982 1300 103. HiÓn thÞ mäi lo¹i nghÒ nghiÖp JOB --------- ANALYST CLERK MANAGER PRESIDENT SALESMAN4. HiÓn thÞ tªn nh©n viªn vµ thu nhËp trong mét n¨m (REMUNERATION) ENAME REMUNERATION ---------- ------------ KING 60000 BLAKE 34200 CLARK 29400 JONES 35700 MARTIN 16400 ALLEN 19500 TURNER 18000 JAMES 11400 WARD 15500 FORD 36000 SMITH 9600 SCOTT 36000 ADAMS 13200 MILLER 15600 14 rows selected.5. HiÓn thÞ theo néi dung d−íi ®©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. HiÓn thÞ cÊu tróc b¶ng emp;7. Thay ®æi nh·n vµ ®Þnh d¹ng hiÓn thÞ cña cét sal vµ hiredate trong b¶ng emp;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 15
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL3 Truy vÊn d÷ liÖu cã ®iÒu kiÖn3.1 MÖnh ®Ò ORDER BYCó ph¸p SELECT [DISTINCT ] {*, column [alias],...} FROM table; [WHERE condition] [ORDER BY expr/position [DESC/ASC]]MÖnh ®Ò ORDER BY dïng ®Ó s¾p xÕp sè liÖu ®−îc hiÓn thÞ vµ ph¶i ®Æt ë vÞ trÝ sau cïng cña c©u lÖnh truyvÊn, VÝ dô: SELECT ENAME, JOB, SAL*12, DEPTNO FROM EMP ORDER BY ENAME;MÖnh ®Ó ORDER BY mÆc ®Þnh s¾p xÕp theo thø tù t¨ng dÇn ASC[ENDING]• Sè thÊp tr−íc• Ngµy nhá tr−íc• Ký tù theo b¶ng ch÷ c¸i§Ó s¾p xÕp theo thø tù ng−îc l¹i (gi¶m dÇn) ®Æt tõ kho¸ DESC[ENDING] sau column cÇn s¾p thø tù. Vi dô: SELECT ENAME, JOB, HIREDATE FROM EMP ORDER BY HIREDATE DESC ;Order nhiÒu columnMÖnh ®Ò Order cßn cã thÓ s¾p xÕp nhiÒu column. C¸c column cÇn s¾p xÕp ®−îc viÕt thø tù sau mÖnh ®ÒORDER BY vµ c¸ch bëi dÊu phÈy (,). Column nµo gÇn mÖnh ®Ó ORDER BY h¬n cã møc ®é −u tiªn khi s¾pxÕp cao h¬n. ChØ ®Þnh c¸ch thøc s¾p xÕp ASC/DESC ®−îc viÕt sau column c¸ch bëi mét dÊu c¸ch. VÝ dô: SELECT DEPTNO, JOB, ENAME, SAL FROM EMP ORDER BY DEPTNO, SAL DESC ;Order gi¸ trÞ NULLRiªng ®èi víi gi¸ trÞ NULL, nÕu s¾p xÕp theo thø tù ASCENDING sÏ n»m ë c¸c vÞ trÝ cuèi cïng.Chó ýCã thÓ chØ ®Þnh s¾p xÕp theo thø tù c¸c column trong mÖnh ®Ò SELECT. VÝ dô: SELECT DEPTNO, JOB, ENAME, SAL FROM EMP ORDER BY 2;3.2 MÖnh ®Ò WHERECó ph¸p SELECT [DISTINCT ] {*, column [alias],...} FROM table; [WHERE condition (s)] [ORDER BY expr/position [DESC/ASC]]§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 16
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLMÖnh ®Ò WHERE dïng ®Ó ®Æt ®iÒu kiÖn cho toµn bé c©u lÖnh truy vÊn. Trong mÖnh ®Ò WHERE cã thÓ cãc¸c thµnh phÇn:• Tªn column• To¸n tö so s¸nh• Tªn column, h»ng sè hoÆc danh s¸ch c¸c gi¸ trÞVÝ dô: SELECT DEPTNO, JOB, ENAME, SAL FROM EMP WHERE SAL BETWEEN 1000 AND 2000 ;Truy vÊn d÷ liÖu víi nhiÒu ®iÒu kiÖnMÖnh ®Ò WHERE cho phÐp ghÐp ®−îc nhiÒu ®iÒu kiÖn th«ng qua c¸c to¸n tö logic AND/OR. To¸n tö ANDyªu cÇu d÷ liÖu ph¶i tho¶ m·n c¶ 2 ®iÒu kiÖn. To¸n tö OR cho phÐp d÷ liÖu tho¶ m·n 1 trong 2 ®iÒu kiÖn. 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, EMPNO, ENAME, SAL FROM EMP WHERE SAL > 1500 AND JOB = ‘MANAGER’ OR JOB =’SALESMAN’; SELECT DEPTNO, JOB, EMPNO, ENAME, SAL FROM EMP WHERE SAL > 1500 AND (JOB = ‘MANAGER’ OR JOB =’SALESMAN’);3.3 C¸c to¸n töTo¸n tö so s¸nh• = : To¸n tö b»ng hay t−¬ng ®−¬ng• !=, ^=, +, <> : To¸n tö kh¸c hay kh«ng t−¬ng ®−¬ng• > : To¸n tö lín h¬n• < : To¸n tö nhá h¬n• >= : To¸n tö lín h¬n hoÆc b»ng• <= : To¸n tö nhá h¬n hoÆc b»ngC¸c to¸n tö logic• NOT : Phñ ®Þnh mÖnh ®Ò• AND : yªu cÇu d÷ liÖu ph¶i tho¶ m·n c¶ 2 ®iÒu kiÖn• OR : cho phÐp d÷ liÖu tho¶ m·n 1 trong 2 ®iÒu kiÖn§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 17
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLC¸c to¸n tö cña SQL• [NOT] BETWEEN x AND y : [Kh«ng] lín h¬n hoÆc b»ng x vµ nhá h¬n hoÆc b»ng y.• IN (danh s¸ch) : thuéc bÊt kú gi¸ trÞ nµo trong danh s¸ch• x [NOT] LIKE y : §óng nÕu x [kh«ng] gièng khung mÉu y. C¸c ký tù dïng trong khu«n mÉu: DÊu g¹ch d−íi ( _ ) : ChØ mét ký tù bÊt kú DÊu phÇn tr¨m ( % ) : ChØ mét nhãm ký tù bÊt kú• IS [NOT] NULL : kiÓm tra gi¸ trÞ rçng• EXISTS : Tr¶ vÒ TRUE nÕu cã tån t¹i.[NOT] BETWEEN x AND yVÝ dô chän nh©n viªn cã l−¬ng n»m trong kho¶ng 2000 vµ 3000 SELECT * FROM emp WHERE sal BETEEN 2000 AND 3000;IN (danh s¸ch)Chän nh©n viªn cã l−¬ng b»ng mét trong 2 gi¸ trÞ 1400 hoÆc 3000 SELECT * FROM emp WHERE sal IN (1400, 3000);T×m tªn phßng ban nÕu phßng ®ã cã nh©n viªn lµm viÖc. SELECT dname FROM dept WHERE EXISTS (SELECT * FROM emp WHERE dept.deptno = emp.deptno);x [NOT] LIKE yT×m nh©n viªn cã tªn b¾t ®Çu b»ng chuçi SMITH SELECT * FROM emp WHERE ename LIKE SMITH_;§Ó chän nh÷ng nh©n viªn cã tªn b¾t ®Çu b»ng SM SELECT * FROM emp WHERE ename LIKE SM%;§Ó t×m nh÷ng nh©n viªn cã tªn cã chuçi A_B SELECT ename FROM emp WHERE ename LIKE %A_B%; ESCAPE V× ký hiÖu "_" dïng ®Ó ®¹i diÖn cho mét ký tù bÊt kú nªn nÕu kh«ng cã mÖnh ®Ò ESCAPE, c©u lÖnh trªn sÏt×m tÊt c¶ c¸c nh©n viªn tªn AAB, ABB, ACB, v.v... (nÕu kh«ng cã mÖnh ®Ò ESCAPE )NÕu muèn ký hiÖu "_" mang ý nghÜa nguyªn thñy, tøc lµ kh«ng cßn ®¹i diÖn cho ký tù bÊt kú n÷a, ta ®Æt dÊu"" tr−íc ký hiÖu. §ång thêi khai b¸o thªm mÖnh ®Ò ESCAPE ""Ta còng cã thÓ dïng mét ký tù bÊt kú thay cho "". Ch¼ng h¹n mÖnh ®Ò sau cã cïng kÕt qu¶ víi mÖnh ®Òtrªn SELECT ename FROM emp WHERE ename LIKE %A^_B%; ESCAPE ^Ta gäi c¸c ký tù nh− "" hay "^" nãi trªn lµ c¸c ký tù ESCAPE.IS [NOT] NULLVÝ duSELECT * FROM emp WHERE comm IS NULL ;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 18
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL3.4 Bµi tËp1. Chän nh©n viªn trong b¶ng EMP cã møc l−¬ng tõ 1000 ®Õn 2000 (chän c¸c tr−êng ENAME, DEPTNO,SAL). ENAME DEPTNO SAL ---------- ---------- ---------- ALLEN 30 1600 WARD 30 1250 MARTIN 30 1250 TURNER 30 1500 ADAMS 20 1100 MILLER 10 1300Sal Between 1000 to 20002.HiÓn thÞ m· phßng ban, tªn phßng ban, s¾p xÕp theo thø tù tªn phßng ban. DEPTNO DNAME ------ ----------- 10 ACCOUNTING 40 OPERATIONS 20 RESEARCH 30 SALESOrder by dname3. HiÓn thÞ danh s¸ch nh÷ng nh©n viªn lµm t¹i phßng 10 vµ 20 theo thø tù A,B,C EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ---------- ----------------- ----- ---------- ---------- ----- ----- 7876 ADAMS CLERK 7788 12-01-1983 1100 20 7782 CLARK MANAGER 7839 09-06-1981 2450 10 7902 FORD ANALYST 7566 03-12-1981 3000 20 7566 JONES MANAGER 7839 02-04-1981 2975 20 7839 KING PRESIDENT 17-11-1981 5000 10 7934 MILLER CLERK 7782 23-01-1982 1300 10 7788 SCOTT ANALYST 7566 09-12-1982 3000 20 7369 SMITH CLERK 7902 17-12-1980 800 20Where deptno in (10,20) order by ename asc4. HiÓn thÞ tªn vµ nghÒ nghiÖp nh÷ng nh©n viªn lµm nghÒ th− ký (clerk) t¹i phßng 20. ENAME JOB ---------- --------- SMITH CLERK ADAMS CLERKWhere upper(job)= upper(clerk) and deptno = 20; (l−u ý vÊn ®Ò ch÷ Hoa-th−êng)5. HiÓn thÞ tÊt c¶ nh÷ng nh©n viªn mµ tªn cã c¸c ký tù TH vµ LL. ENAME ---------- SMITH ALLEN MILLERWhere ename like “%TH%“ or ename like “%LL%“6. HiÓn thÞ tªn nh©n viªn, nghÒ nghiÖp, l−¬ng cña nh÷ng nh©n viªn cã gi¸m ®èc qu¶n lý. ENAME JOB SAL ---------- --------- ---------- SMITH CLERK 800 ALLEN SALESMAN 1600 WARD SALESMAN 1250 JONES MANAGER 2975§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 19
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL MARTIN SALESMAN 1250 BLAKE MANAGER 2850 CLARK MANAGER 2450 SCOTT ANALYST 3000 TURNER SALESMAN 1500 ADAMS CLERK 1100 JAMES CLERK 950 FORD ANALYST 3000 MILLER CLERK 1300 13 rows selected.7. HiÓn thÞ tªn nh©n viªn, m· phßng ban, ngµy gia nhËp c«ng ty sao cho gia nhËp c«ng ty trong n¨m 1983. ENAME DEPTNO HIREDATE ---------- ---------- --------- ADAMS 20 12-JAN-83Where to_char(hiredate) like “%83“Where hiredate like “%83“8. HiÓn thÞ tªn nh©n viªn, l−¬ng mét n¨m (ANUAL_SAL ), th−ëng sao cho l−¬ng lín h¬n th−ëng vµ nghÒnghiÖp lµ SALEMAN, s¾p theo thø tù l−¬ng gi¶m dÇn vµ tªn t¨ng dÇn. ANUAL_SAL COMM ---------- ---------- 19200 300 18000 0 15000 5004 C¸c hµm ¸p dông cho 1 dßng d÷ liÖu4.1 C¸c hµm sè§Çu vµo vµ ®Çu ra lµ c¸c gi¸ trÞ kiÓu sèROUND(n[,m]) cho gi¸ trÞ lµm trßn cña n (®Õn cÊp m, mÆc nhiªn m=0)TRUNC(n[,m]) cho gi¸ trÞ n lÊy m ch÷ sè tÝnh tõ chÊm thËp ph©n = Format(dl, “99999,00“)CEIL(n) cho sè nguyªn nhá nhÊt lín h¬n hoÆc b»ng n =FLOOR(n) cho sè nguyªn lín nhÊt b»ng hoÆc nhá h¬n n =POWER(m,n) cho lòy thõa bËc n cña m =EXP(n) cho gi¸ trÞ cña en =SQRT(n) cho c¨n bËc 2 cña n, n>=0 =SIGN(n) cho dÊu cña n. = n<0 cã SIGN(n)= -1 n=0 cã SIGN(n)= 0 n>0 cã SIGN(n)= 1ABS(n) cho gi¸ trÞ tuyÖt ®èi =MOD(m,n) cho phÇn d− cña phÐp chia m cho n =Mét sè hµm kiÓu sè tham kh¶o kh¸c:LOG(m,n) cho logarit c¬ sè m cña n =§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 20
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLSIN(n) cosin cña n (n tÝnh b»ng radian) =COS(n) cho cosin cña n (n tÝnh b»ng radian) =TAN(n) cotang cña n (n tÝnh b»ng radian) =VÝ dô hµm 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.92VÝ dô hµm 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.92VÝ dô hµm 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 100 102 -11 3000 100 102 -11 3000 100 102 -11VÝ dô hµm 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 99 101 -12 3000 99 101 -12 3000 99 101 -12VÝ dô hµm POWER(m,n) SELECT SAL, POWER(SAL,2), POWER(SAL,3), POWER(50,5) FROM EMP WHERE DEPTNO =10; SAL POWER(SAL,2) POWER(SAL,3) POWER(50,5) ---------- ------------ ------------ ----------- 5000 25000000 1.2500E+11 312500000 2450 6002500 1.4706E+10 312500000 1300 1690000 2197000000 312500000VÝ dô hµm EXP(n) SELECT EXP(4) FROM DUMMY; EXP(4)§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 21
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL ---------- 54.59815VÝ dô hµm SQRT(n) SELECT SAL, SQRT(SAL), SQRT(40), SQRT (COMM) FROM EMP WHERE DEPTNO =10; SAL SQRT(SAL) SQRT(40) SQRT(COMM) ---------- ---------- ---------- ---------- 5000 70.7106781 6.32455532 2450 49.4974747 6.32455532 1300 36.0555128 6.32455532VÝ dô hµm 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 1 -2850 -1 -150 -1 150 1 1300 1 -1300 -1 1500 1 -1500 -1 950 1 -950 -1 750 1 -750 -14.2 C¸c hµm ký tùCONCAT(char1, char2) cho kÕt hîp cña 2 chuçi ký tù, t−¬ng tù nh− sö dông to¸n tö ||INITCAP(char) cho chuçi víi ký tù ®Çu c¸c tõ lµ ký tù hoaLOWER(char) cho chuçi ký tù viÕt th−êng (kh«ng viÕt hoa)LPAD(char1, n [,char2]) cho chuçi ký tù cã chiÒu dµi b»ng n. NÕu chuçi char1 ng¾n h¬n n th× thªm vµo bªn tr¸i chuçi char2 cho ®ñ n ký tù. NÕu chuçi char1 dµi h¬n n th× gi÷ l¹i n ký tõ tÝnh tõ tr¸i sangLTRIM(char1, n [,char2]) bá c¸c ký tù trèng bªn tr¸iNLS_INITCAP(char) cho chuçi víi ký tù ®Çu c¸c tõ lµ ch÷ hoa, c¸c ch÷ cßn l¹i lµ ch÷ th−êngREPLACE(char,search_string[,replacement_string]) : thay tÊt c¶ c¸c chuçi search_string cã trong chuçi char b»ng chuçi replacement_string.RPAD(char1, n [,char2]) Gièng LPAD(char1, n [,char2]) nh−ng c¨n ph¶iRTRIM(char1, n [,char2]) bá c¸c ký tù trèng bªn ph¶iSOUNDEX(char) cho chuçi ®ång ©m cña char.SUBSTR(char, m [,n]) cho chuçi con cña chuçi char lÊy tõ vÞ trÝ m vÕ ph¶i n ký tù, nÕu kh«ng chØ n th× lÊy cho ®Õn cuèi chuçiTRANSLATE(char, from, to) cho chuçi trong ®ã mçi ký tù trong chuçi from thay b»ng ký tù t−¬ng øng trong chuçi to, nh÷ng ký tù trong chuçi from kh«ng cã t−¬ng øng trong chuçi to sÏ bÞ lo¹i bá.UPPER(char) cho chuçi ch÷ hoa cña chuçi char§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 22
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLASCII(char) cho ký tù ASCII cña byte ®Çu tiªn cña chuçi charINSTR(char1, char2 [,n[,m]]) t×m vÞ trÝ chuçi char2 trong chuçi char1 b¾t ®Çu tõ vÞ trÝ n, lÇn xuÊt hiÖn thø m.LENGTH(char) cho chiÒu dµi cña chuçi charVÝ dô hµm LOWER(char) SELECT LOWER(DNAME), LOWER(‘SQL COURSE’) FROM DEPT; LOWER(DNAME) LOWER(SQL -------------- ---------- accounting sql course research sql course sales sql course operations sql courseVÝ dô hµm UPPER(char) SELECT ENAME FROM EMP WHERE ENAME = UPPER(‘Smith’); ENAME ---------- SMITHVÝ dô hµm INITCAP(char) SELECT INITCAP(DNAME), INITCAP(LOC) FROM DEPT; INITCAP(DNAME) INITCAP(LOC) -------------- ------------- Accounting New York Research Dallas Sales Chicago Operations BostonVÝ dô hµm CONCAT(char1, char2) SELECT CONCAT(ENAME, JOB) JOB FROM EMP WHERE EMPNO = 7900; JOB ------------------- JAMES CLERKVÝ dô hµm LPAD(char1, n [,char2]) SELECT LPAD(DNAME,20,’*’), LPAD(DNAME,20), LPAD(DEptno,20,’ ’) FROM DEPT; LPAD(DNAME,20,*) LPAD(DNAME,20) LPAD(DEPTNO,20,) -------------------- -------------------- -------------------- ******ACCOUNTING ACCOUNTING 10 ******RESEARCH RESEARCH 20 ******SALES SALES 30 ******OPERATIONS OPERATIONS 40VÝ dô hµm RPAD(char1, n [,char2]) SELECT RPAD(DNAME,20,’*’), RPAD(DNAME,20), RPAD(DEptno,20,’ ’) FROM DEPT;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 23
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL RPAD(DNAME,20,*) RPAD(DNAME,20) RPAD(DEPTNO,20,) -------------------- -------------------- -------------------- ACCOUNTING ****** ACCOUNTING 10 RESEARCH ****** RESEARCH 20 SALES ****** SALES 30 OPERATIONS ****** OPERATIONS 40VÝ dô hµm SUBSTR(char, m [,n]) SELECT SUBSTR(‘ORACLE’,2,4), SUBSTR(DNAME,2), SUBSTR(DNAME,3,5) FROM DEPT; SUBS SUBSTR(DNAME, SUBST ---- ------------- ----- RACL CCOUNTING COUNT RACL ESEARCH SEARC RACL ALES LES RACL PERATIONS ERATIVÝ dô hµm INSTR(char1, char2 [,n[,m]]) SELECT DNAME, INSTR(DNAME, ‘A’), INSTR(DNAME,’ES’), INSTR(DNAME,’C’,1,2) FROM DEPT; DNAME INSTR(DNAME,A) INSTR(DNAME,ES) INSTR(DNAME,C,1,2) -------------- ---------------- ----------------- -------------------- ACCOUNTING 1 0 3 RESEARCH 5 2 0 SALES 2 4 0 OPERATIONS 5 0 0VÝ dô hµm LTRIM(char1, n [,char2]) SELECT DNAME, LTRIM(DNAME,’A’), LTRIM(DNAME,’AS’), LTRIM(DNAME,’ASOP’) FROM DEPT; DNAME LTRIM(DNAME,A LTRIM(DNAME,A LTRIM(DNAME,A -------------- -------------- -------------- -------------- ACCOUNTING CCOUNTING CCOUNTING CCOUNTING RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES LES LES OPERATIONS OPERATIONS OPERATIONS ERATIONSVÝ dô hµm RTRIM(char1, n [,char2]) SELECT DNAME, RTRIM(DNAME,’A’), RTRIM(DNAME,’AS’), RTRIM(DNAME,’ASOP’) FROM DEPT; DNAME RTRIM(DNAME,A RTRIM(DNAME,A RTRIM(DNAME,A -------------- -------------- -------------- -------------- ACCOUNTING ACCOUNTING ACCOUNTING ACCOUNTING RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES SALES SALES OPERATIONS OPERATIONS OPERATIONS OPERATIONSVÝ dô hµm SOUNDEX(char) SELECT ENAME, SOUNDEX(ENAME) FROM EMP WHERE SOUNDEX(ENAME)= SOUNDEX(‘FRED’); ENAME SOUN ---------- ---- FORD F630VÝ dô hµm LENGTH(char) SELECT LENGTH(‘SQL COURSE’), LENGTH(DEPTNO), LENGTH(DNAME) FROM DEPT;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 24
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 25
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL LENGTH(SQLCOURSE) LENGTH(DEPTNO) LENGTH(DNAME) ------------------- -------------- ------------- 10 2 14 10 2 14 10 2 14 10 2 14VÝ dô hµm TRANSLATE(char, from, to) SELECT ENAME, TRANSLATE(ENAME,C,F), JOB, TRANSLATE(JOB,AR,IT) FROM EMP WHERE DEPTNO = 10; ENAME TRANSLATE( JOB TRANSLATE ---------- ---------- --------- --------- KING KING PRESIDENT PTESIDENT CLARK FLARK MANAGER MINIGET MILLER MILLER CLERK CLETKVÝ dô hµm 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 REPLACE(ENAME,CO, --------- ----------------------- --------- --------------- MANAGER MANAGER BLAKE BLAKE MANAGER MANAGER JONES JONES SALESMAN SALESPERSON MARTIN MARTIN SALESMAN SALESPERSON ALLEN ALLEN SALESMAN SALESPERSON TURNER TURNER CLERK CLERK JAMES JAMES SALESMAN SALESPERSON WARD WARD ANALYST ANALYST FORD FORD CLERK CLERK SMITH SMITH ANALYST ANALYST SCOTT SPRTT CLERK CLERK ADAMS ADAMSVÝ dô c¸c hµm lång nhau: SELECT DNAME, LENGHT(DNAME), LENGHT(TRANSLATE,DNAME, ‘AS’,’A’)) FROM DEPT; DNAME LENGTH(DNAME) LENGTH(TRANSLATE(DNAME,AS,A)) -------------- ------------- --------------------------------- ACCOUNTING 14 14 RESEARCH 14 13 SALES 14 12 OPERATIONS 14 134.3 C¸c hµm ngµyMONTH_BETWEEN(d1, d2) cho biÕt sã th¸ng gi÷a ngµy d1 vµ d2.ADD_MONTHS(d,n) cho ngµy d thªm n th¸ng.NEXT_DAY(d, char ) cho ngµy tiÕp theo ngµy d cã thø chØ bëi char.LAST_DAY(d) cho ngµy cuèi cïng trong th¸ng chØ bëi d.VÝ dô hµm MONTH_BETWEEN(d1, d2) SELECT MONTHS_BETWEEN( SYSDATE, HIREDATE), MONTHS_BETWEEN(01-01-2000,05-10-2000)§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 26
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL FROM EMP WHERE MONTHS_BETWEEN( SYSDATE,HIREDATE)>240; MONTHS_BETWEEN(SYSDATE,HIREDATE) TWEEN(01-01-2000,05-10-2000) -------------------------------- -------------------------------- 241.271055 -9.1290323 241.206539 -9.1290323 243.367829 -9.1290323VÝ dô hµm ADD_MONTHS(d,n) SELECT HIREDATE, ADD_MONTHS(HIRE,3), ADD_MONTHS(HIREDATE,-3) FROM EMP WHERE DEPTNO=20; 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-1982VÝ dô hµm NEXT_DAY(d, char ) SELECT HIREDATE, NEXT_DAY(HIREDATE,’FRIDAY’), NEXT_DAY(HIREDATE,6) FROM EMP WHERE DEPTNO = 10; 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-1982VÝ dô hµm LAST_DAY(d) SELECT SYSDATE, LAST_DAY(SYSDATE), HIREDATE, LAST_DAY(HIREDATE), LAST_DAY(’15-01-2001’) FROM EMP WHERE DEPTNO =20; SYSDATE LAST_DAY(S HIREDATE LAST_DAY(H LAST_DAY( ---------- ---------- ---------- ---------- ---------- 28-03-2001 31-03-2001 02-04-1981 30-04-1981 31-01-2001 28-03-2001 31-03-2001 03-12-1981 31-12-1981 31-01-2001 28-03-2001 31-03-2001 17-12-1980 31-12-1980 31-01-2001 28-03-2001 31-03-2001 09-12-1982 31-12-1982 31-01-2001 28-03-2001 31-03-2001 12-01-1983 31-01-1983 31-01-2001Mét sè hµm kh¸c cã thÓ ¸p dông cho kiÓu ngµy:ROUND(date1) tr¶ vÒ ngµy date 1 t¹i thêi ®iÓm gi÷a tr−a 12:00 AMROUND(date1,’MONTH’) NÕu date 1 n»m trong nöa th¸ng ®Çu tr¶ vÒ ngµy ®Çu tiªn cña thµng, ng−îc l¹i sÏ tr¶ vÒ ngµy ®Çu tiªn cña th¸ng sau.ROUND(date1,’YEAR’) NÕu date 1 n»m trong nöa n¨m ®Çu tr¶ vÒ ngµy ®Çu tiªn cña thµng, ng−îc l¹i sÏ tr¶ vÒ ngµy ®Çu tiªn cña n¨m sau.TRUNC(date1, ’MONTH’) Tr¶ vÒ ngµy ®Çu tiªn cña th¸ng chøa date1TRUNC(date1, ’YEAR’) Tr¶ vÒ ngµy ®Çu tiªn cña n¨m chøa date1§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 27
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL4.4 C¸c hµm chuyÓn ®æi kiÓuTO_CHAR(number|date, ‘fmt’) ChuyÓn kiÓu sè vµ ngµy vÒ kiÓu ký tù.TO_NUMBER(char) ChuyÓn ký tù cã néi dung sè sang sèTO_DATE(‘chsr’,’fmt’) ChuyÓn ký tù sang kiÓu ngµy víi ®Þnh d¹ng ®Æt trong fmt.DECODE(EXPR, SEARCH1, RESULT1, SEARCH2, RESULT2, DEFAULT): So s¸nh biÓu thøc expr víi gi¸ trÞ search nÕu ®óng tr¶ vÒ gi¸ trÞ result nÕu kh«ng tr¶ vÒ gi¸ trÞ default.NVL(COL|VALUE, VAL) ChuyÓn gi¸ trÞ COL|VALUE thµnh val nÕu null.Greatest(col|value1, col|value2) Tr¶ gi¸ trÞ lín nhÊt trong d·y gi¸ trÞ.Vd: 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’) DECODÑD_JOB FROM EMP; SELECT GREATEST(1000,2000), GREATEST(SAL,COMM) FROM EMP WHERE DEPTNO = 10;Mét sè khu«n d¹ng ngµy SCC hoÆc CC thÕ kû; S chØ ngµy BC YYYY hoÆc SYYYY n¨m; S chØ ngµy BC YYY, YY, Y ChØ n¨m víi 3,2,1 ký tù sè IYYY, IYY, IY, I ChØ n¨m theo chuÈn ISO SYEAR, YEAR ChØ n¨m theo c¸ch ph¸t ©m cña ng−êi anh; Q Quý trong n¨m MM Gi¸ trÞ th¸ng víi 2 sè (01-12) MONTH Tªn ®Çy ®ñ cña th¸ng theo tiÕng anh, ®ä dµi 9 MON Th¸ng víi 3 ký tù viÕn t¾t (JAN, FEB...) WW, W TuÇn trong n¨m hoÆc trong th¸ng DDD, DD, D Ngµy trong n¨m, th¸ng hoÆc tuÇn DAY ChØ thø trong tuÇn DY ChØ thø trong tuÇn víi 3 ký tù viÕt t¾t J Ngµy Julian; b¾t ®Çu tõ ngµy 31/12/4713 tr−íc c«ng nguyªn AM, PM ChØ ®Þnh s¸ng, chiÒu HH, HH12 HH24 ChØ giê trong ngµy (1-12) hoÆc (0-23) MI Phót (0-59) SS Gi©y (0-59) SSSSS Sè gi©y ®Õn nöa ®ªm (0-86399) / . , - ®−îc tù ®éng thªm khi ®Æt trong khu«n d¹ng “char” §o¹n ký tù ®Æt trong nh¸y ®óp ®−îc tù ®éng thªm khi ®Æt trong khu«n d¹ng TH Thªm phÇn thø tù (1st, 2nd, 4th ) SP Ph¸t ©m sè ( FOUR víi DDSP)§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 28
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL SPTH, THSP Ph¸t ©m vµ chuyÓn sang d¹ng thø tù ( First, second, ...) RR Ngµy chuyÓn giao thiªn niªn kû víi c¸c n¨m <1999. N¨m 0-49 50-99 N¨m hiÖn 0-49 thÕ kû hiÖn ThÕ kû t¹i t¹i sau 50-99 ThÕ kû tr−íc ThÓ kû hiÖn t¹iMét sè khu«n d¹ng sè Ký M« t¶ VÝ dô KÕt qu¶ tù 9 X¸c ®Þnh hiÓn thÞ 1 sè 999999 1234 0 HiÓn thÞ c¶ sè 0 ë ®Çu nÕu ®é 099999 001234 dµi khu«n d¹ng lín h¬n sè hiÖn cã $ Thªm ký tù tiÒn tÖ $999999 $1234 L Thªm ký tù tiÒn tÖ b¶n ®Þa L999999 FF1234 . DÊu thËp ph©n 999999.99 1234.00 , DÊu ph©n c¸ch phÇn ngh×n 999,999 1,234 MI DÊu ©m ë bªn ph¶i ( víi c¸c 999999MI 1234- gi¸ trÞ ©m) PR Thªm ngoÆc nhän vµo c¸c gi¸ 999999PR <1234> trÞ ©m EEE ChuyÓn sang hiÓn thÞ sè E 99.9999RRRR 1.234E+03 V Nh©n víi 10 n, n lµ sè c¸c sè 9999V99 123400 9 ®Æt sau V B HiÓn thÞ c¶ gi¸ trÞ 0 nÕu = B9999.99 1234.00 0.4.5 Bµi tËp1. LiÖt kª tªn nh©n viªn, m· phßng ban vµ l−¬ng nh©n viªn ®−îc t¨ng 15% (PCTSAL). DEPTNO ENAME PCTSAL ---------- ---------- ---------- 10 KING 5000 30 BLAKE 2850 10 CLARK 2450 20 JONES 2975 30 MARTIN 1250 30 ALLEN 1600 30 TURNER 1500 30 JAMES 950 30 WARD 1250 20 FORD 3000 20 SMITH 800 20 SCOTT 3000 20 ADAMS 1100 10 MILLER 13002. ViÕt c©u lÖnh hiÓn 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§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 29
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL SMITH**********CLERK SCOTT********ANALYST ADAMS**********CLERK MILLER*********CLERK3. ViÕt c©u lÖnh hiÓn 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. ViÕt c©u lÖnh hiÓn thÞ nh− sau: ENAME DEPTNO JOB ---------- ---------- --------------- BLAKE 30 Manager MARTIN 30 Salesperson ALLEN 30 Salesperson TURNER 30 Salesperson JAMES 30 Clerk WARD 30 Salesperson5. T×m ngµy thø 6 ®Çu tiªn c¸ch 2 th¸ng so víi ngµy hiÖn t¹i hiÓn thÞ ngµy d−íi d¹ng 09 February 1990.6. T×m th«ng itn vÒ tªn nh©n viªn, ngµy gia nhËp c«ng ty cña nh©n viªn phßng sè 20, sao cho hiÓn thÞ nh−sau: ENAME DATE_HIRED ---------- -------------------------- JONES april,SECOND 1981 FORD december,THIRD 1981 SMITH december,SEVENTEENTH 1980 SCOTT december,NINTH 1982 ADAMS january,TWELFTH 19837. HiÓn thÞ tªn nh©n viªn, ngµy gia nhËp c«ng ty, ngµy xÐt n©ng l−¬ng (sau ngµy gia nhËp c«ng ty 1 n¨m),s¾p xÕp theo thø tù ngµy xÐt n©ng l−¬ng. ENAME HIREDATE REVIEW ---------- ---------- ---------- SMITH 17-12-1980 17-12-1981 ALLEN 20-02-1981 20-02-1982 WARD 22-02-1981 22-02-1982 JONES 02-04-1981 02-04-1982 BLAKE 01-05-1981 01-05-1982 CLARK 09-06-1981 09-06-1982 TURNER 08-09-1981 08-09-1982 MARTIN 28-09-1981 28-09-1982 KING 17-11-1981 17-11-1982 JAMES 03-12-1981 03-12-1982 FORD 03-12-1981 03-12-1982 MILLER 23-01-1982 23-01-1983 SCOTT 09-12-1982 09-12-1983 ADAMS 12-01-1983 12-01-19848.HiÓn thÞ tªn nh©n viªn vµ l−¬ng d−íi d¹ng§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 30
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL ENAME SALARY ---------- ------------ ADAMS BELOW 1500 ALLEN 1600 BLAKE 2850 CLARK 2450 FORD 3000 JAMES BELOW 1500 JONES 2975 KING 5000 MARTIN BELOW 1500 MILLER BELOW 1500 SCOTT 3000 SMITH BELOW 1500 TURNER On Target WARD BELOW 15009. Cho biÕt thø cña ngµy hiÖn t¹i10. §−a chuçi d−íi d¹ng nn/nn, kiÓm tra nÕu khóng khu«n d¹ng tr¶ lêi lµ YES, ng−îc l¹i lµ no. KiÓm tra víic¸c chuçi 12/34, 01/1a, 9988 VALUE VALID? ----- ------- 12/34 YES11. HiÓn thÞ tªn nh©n viªn, ngµy gia nhËp c«ng ty, ngµy lÜnh l−¬ng sao cho ngµy lÜnh l−¬ng ph¶i vµo thø 6,nh©n viªn chØ ®−îc nhËn l−¬ng sau Ýt nhÊt 15 ngµy lµm viÖc t¹i c«ng ty, s¾p xÕp theo thø tù ngµy gia nhËpc«ng ty.5 BiÕn runtimeD÷ liÖu thay thÕ trong c©u lÖnhDïng (&) ®Ó chØ phÇn thay thÕ trong c©u lÖnh.NÕu dïng (&&) chØ biÕn thay thÕ th× sau c©u lÖnh biÕn thay thÕ vÉn cßn tån t¹iVÝ dô SELECT * FROM emp WHERE &Condition Enter value for condition: sal > 1000 Khi Êy c©u lÖnh trªn t−¬ng ®−¬ngSELECT * FROM empWHERE sal > 1000VÝ du 2: Select ename, deptno, job From emp Where deptno = &&depno_please;LÖnh DefineKhai b¸o vµ g¸n trÞ cho c¸c biÕn, vÝ dô khai b¸o biÕn condition cã tri sal > 1000 DEFINE condition = sal > 1000Khi ®ã c©u lÖnh sau kh«ng yªu cÇu nhËp vµo gi¸ trÞ cho codition SELECT * FROM emp WHERE &Condition§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 31
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL§Ó lo¹i bá biÕn ra khái bé nhí dïng lÖnh UNDEFINE, vÝ dô UNDEFINE condition§Ó liÖt kª c¸c biÕn ®· khai b¸o dïng lÖnh DEFINE mµ kh«ng chØ biÕn, vÝ dô DEFINE DEFINE CONDITION = SAL > 1000VÝ dô: DEFINE REM=’SAL*12+NVL(COMM,0)’ SELECT ENAME, JOB, &REM FROM EKP ORDER BY & REM;LÖnh AcceptKhai b¸o vµ g¸n trÞ cho biÕn víi dßng hiÓn thÞ ACCEPT variable [NUMBER/CHAR] [PROMPT/NOPROMPT text] HIDEVÝ dô ACCEPT Salary NUMBER PROMPT Salary figure: Salary figure : 3000Tõ kho¸ hide cho phÐp che chuçi nhËp liÖu, hay dïng khi nhËp password. ACCEPT password CHAR PROMPT Enter password: HIDE Password : ******5.1 Bµi tËp1. HiÓn thÞ tªn nh©n viªn, ngµy gia nhËp c«ng ty víi ®iÒu kiÖn ngµy gia nhËp c«ng ty n»m trong kho¶ng haibiÕn runtime ®−îc nhËp vµo tõ bµn phÝm (&first_date, &last_date).2. HiÓn thÞ tªn nh©n viªn, nghÒ nghiÖp, l−¬ng, m· gi¸m ®èc, m· phßng ban víi ®iÒu kiÖn nghÒ nghiÖp b»ngmét biÕn ®−îc nhËp vµo tõ bµn phÝm. (&job)3. §Þnh nghÜa mét biÕn tÝnh thu nhËp mét n¨m cña nh©n viªn. Dïng biÕn nµy ®Ó t×m nh÷ng nh©n viªn cã thunhËp lín h¬n hoÆc b»ng $30000.4. §Þnh nghÜa mét biÕn lµ kho¶ng thêi gian nh©n viªn lµm trong c«ng ty. HiÓn thÞ tªn nh©n viªn vµ qu·ng thêigian nh©n viªn ®ã lµm viÖc víi ®iÒu kiÖn nh©n viªn lµ mét biÕn ®−îc nhËp vµo tõ bµn phÝm. ENAME LENGTH OF SERVICE ---------- --------------------- KING 19 YEAR 4 MONTHS6 C¸c hµm nhãm ¸p dông cho lín h¬n hoÆc b»ng 1 dßng d÷ liÖu6.1 C¸c hµm t¸c ®éng trªn nhãmC¸c hµm t¸c ®éng trªn nhãm c¸c dßng d÷ liÖu t¸c ®éng lªn mét tËp hîp c¸c c¸c dßng d÷ liÖu. Gåm c¸chµm:AVG([DISTINCT/ALL] n) Gi¸ trÞ trung b×nh cña n,kh«ng kÓ trÞ nullCOUNT([DISTINCT/ALL] expr) Sè row cã expr kh¸c nullMAX([DISTINCT/ALL] expr) Gi¸ trÞ lín nhÊt cña exprMIN([DISTINCT/ALL] expr) Gi¸ trÞ nhá nhÊt cña exprSTDDVE([DISTINCT/ALL] n) Ph−¬ng sai cña n kh«ng kÓ trÞ null§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 32
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLSUM([DISTINCT/ALL] n) Tæng cña cña n kh«ng kÓ trÞ nullVARIANCE([DISTINCT/ALL] n) Variance cña n kh«ng kÓ trÞ nullChó ý tÊt c¶ c¸c hµm trªn nhãm mÉu tin ®Òu bá qua gi¸ trÞ NULL trõ hµm COUNT. Dïng hµm NVL ®ÓchuyÓn ®æi vµ tÝnh gi¸ trÞ NULL.Cã 2 c¸ch ®Ó dïng c¸c c¸c hµm nµy• T¸c ®éng trªn toµn bé c¸c dßng d÷ liÖu cña c©u lÖnh truy vÊn• T¸c ®éng trªn mét nhãm d÷ liÖu cïng tÝnh chÊt cña c©u lÖnh truy vÊn. Cïng tÝnh chÊt ®−îc chØ bëi mÖnh ®Ò [GROUP BY expr] [HAVING condition]§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 33
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLVÝ dô T¸c ®éng trªn toµn bé c¸c dßng d÷ liÖu cña c©u lÖnh truy vÊn: Select AVG(SAL) FROM EMP: /TÝnh møc l−¬ng trung b×nh cña toµn bé nh©n viªn / Select MIN(SAL) FROM EMP WHERE JOB =’CLERK’: /TÝnh møc l−¬ng thÊp nhÊt cña nh©n viªn lµm nghÒ CLERK /VÝ dô t¸c ®éng trªn mét nhãm d÷ liÖu cïng tÝnh chÊt cña c©u lÖnh truy vÊn. SELECT JOB, AVG(SAL) FROM EMP GROUP BY JOB; / TÝnh møc l−¬ng trung b×nh cña tõng lo¹i nghÒ nghiÖp/Chó ý: ChØ ®−îc cïng ®Æt trong mÖnh ®Ó SELECT c¸c hµm nhãm hoÆc c¸c column ®· ®Æt trong mÖnh ®ÒGROUP BY. VÝ dô §óng: SELECT MAX(SAL), JOB FROM EMP GROUP BY JOB; Sai: SELECT MAX(SAL), JOB FROM EMP;6.2 MÖnh ®Ò GROUP BYCó ph¸p: SELECT [DISTINCT ] {*, column [alias],...} FROM table; [WHERE condition] [GROUP BY expr] [HAVING [HAVING condition] [ORDER BY expr/position [DESC/ASC]]MÖnh ®Ò GROUP BY sÏ nhãm c¸c dßng d÷ liÖu cã cïng gi¸ trÞ cña expr. VÝ dô GROUP BY JOB nghÜa lµ sÏnhãm c¸c nghÒ gièng nhau.MÖnh ®Ò HAVING lµ ®Æt ®iÒu kiÖn cña nhãm d÷ liÖu. MÖnh ®Ò nµy kh¸c mÖnh ®Ò WHERE ë chç mÖnh ®ÒWHERE ®Æt ®iÒu kiÖn cho toµn bé c©u lÖnh SELECT. VÝ dô: SELECT JOB, MAX(SAL) FROM EMP WHERE JOB !=’MANAGER’ GROUP BY JOB; JOB MAX(SAL) --------- ---------- ANALYST 3000 CLERK 1300 PRESIDENT 5000 SALESMAN 1600 SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB HAVING COUNT(*)>3; JOB MAX(SAL) --------- ---------- CLERK 1300 SALESMAN 1600 SELECT JOB, MAX(SAL) FROM EMP§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 34
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL HAVING MAX(SAL)>=3000 GROUP BY JOB; JOB MAX(SAL) --------- ---------- ANALYST 3000 PRESIDENT 50006.3 Bµi tËp1. T×m l−¬ng thÊp nhÊt, lín nhÊt vµ l−¬ng trung b×nh cña tÊt c¶ c¸c nh©n viªn2. t×m l−¬ng nhá nhÊt vµ lín cña mçi lo¹i nghÒ nghiÖp3. T×m xem cã bao nhiªu gi¸m ®èc trong danh s¸ch nh©n viªn.4. T×m tÊt c¶ c¸c phßng ban mµ sè nh©n viªn trong phßng >35. T×m ra møc l−¬ng nhá nhÊt cña mçi nh©n viªn lµm viÖc cho mét gi¸m ®èc nµo ®ã s¾p xÕp theo thø tù t¨ngdÇn cña møc l−¬ng.7 HiÓn thÞ néi dung d÷ liÖu tõ nhiÒu b¶ng7.1 Mèi liªn kÕt t−¬ng ®−¬ng• Mèi liªn kÕt t−¬ng ®−¬ng ®−îc thÓ hiÖn trong mÖnh ®Ó WHERE.• §Ó liªn kÕt trong mÖnh ®Ó WHERE ph¶i chØ râ tªn cña c¸c column vµ mÖnh ®Ò ®−îc ®Æt t−¬ng ®−¬ng. Vd: emp.deptno =dept.deptno• C¸c column trïng tªn ph¶i ®−îc chØ râ column ®ã n»m ë b¶ng n¶o th«ng qua tªn hoÆc qua alias. Tªn trïng nµy cã thÓ ®Æt trong c¸c mÖnh ®Ò kh¸c nh− SELECT, ORDER BY.. Vd: SELECT DEPT.DEPTNO, ENAME,JOB, DNAME FROM EMP, DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO ORDER BY DEPT.DEPTNO; SELECT A.DEPTNO, A.ENAME, A.JOB, B.DNAME FROM EMP A, DEPT B WHERE A.DEPTNO = B.DEPTNO ORDER BY A.DEPTNO;7.2 Mèi liªn kÕt kh«ng t−¬ng ®−¬ng• Mèi liªn kÕt t−¬ng ®−¬ng ®−îc thÓ hiÖn trong mÖnh ®Ó WHERE.• §Ó liªn kÕt trong mÖnh ®Ó WHERE ph¶i chØ râ tªn cña c¸c column vµ mÖnh ®Ò ®−îc ®Æt KH¤NG t−¬ng ®−¬ng. Vd: WHERE E.SAL BETWEEN S. LOSAL AND S.HISAL• C¸c column trïng tªn ph¶i ®−îc chØ râ column ®ã n»m ë b¶ng nµo th«ng qua tªn hoÆc qua alias. Tªn trïng nµy cã thÓ ®Æt trong c¸c mÖnh ®Ò kh¸c nh− SELECT, ORDER BY.. VD: SELECT E.ENAME,E.JOB, S.GRADE FROM EMP E, SALGRADE S WHERE E.SAL BETWEEN S. LOSAL AND S.HISAL;§iÒu kiÖn liªn kÕt ®óng lµ sè c¸c b¶ng - 1 = sè c¸c ®iÒu kiÖn liªn kÕt§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 35
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL7.3 Mèi liªn kÕt céng• Mèi liªn kÕt céng tr¶ vÒ c¶ c¸c gi¸ trÞ NULL trong biÓu thøc ®iÒu kiÖn. DÊu (+) ®Ó ë vÕ nµo tÝnh thªm c¸c gi¸ trÞ NULL ë vÕ ®ã.• Mét c©u lÖnh select chØ ®Æt ®−îc 1 mèi liªn kÕt céng, dÊu (+) ®Æt ë bªn ph¶i column liªn kÕt• Trong mÖnh ®Ò WHERE cña mèi liªn kÕt céng kh«ng ®−îc dïng to¸n tö IN hoÆc OR ®Ó nèi c¸c ®iÒu kiÖn liªn kÕt kh¸c. Vd: SELECT E.ENAME, D.DEPTNO, D.DNAME FROM EMP E, DEPT D WHERE E.DEPTNO (+)=D.DEPTNO AND D.DEPTNO IN (30, 40); ENAME DEPTNO DNAME ---------- ---------- ------------- BLAKE 30 SALES MARTIN 30 SALES ALLEN 30 SALES TURNER 30 SALES JAMES 30 SALES WARD 30 SALES 40 OPERATIONS7.4 Liªn kÕt cña b¶ng víi chÝnh nãCã thÓ liªn kÐt b¶ng víi chÝnh nã b»ng c¸ch ®Æ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 EMP_SAL MGR_NAME MGR_SAL ---------- ---------- ---------- ---------- BLAKE 2850 KING 5000 CLARK 2450 KING 5000 JONES 2975 KING 5000 MARTIN 1250 BLAKE 2850 ALLEN 1600 BLAKE 2850 TURNER 1500 BLAKE 2850 JAMES 950 BLAKE 2850 WARD 1250 BLAKE 2850 SMITH 800 FORD 3000 ADAMS 1100 SCOTT 3000 MILLER 1300 CLARK 24507.5 C¸c to¸n tö tËp hîpUNION KÕt hîp kÕt qu¶ cña nhiÒu c©u hái víi nhau, chØ gi÷ l¹i mét ®¹i diÖn cho c¸c mÉu tin trïng nhau.UNION ALL KÕt hîp kÕt qu¶ cña nhiÒu c©u hái víi nhau, c¸c mÉu tin trïng nhau còng ®−îc lÆp l¹iINTERSET LÊy phÇn giao c¸c kÕt qu¶ cña nhiÒu c©u háiMINUS LÊy kÕt qu¶ cã trong c©u hái thø nhÊt mµ kh«ng cã trong c©u hái thø hai (c©u hái sau to¸n tö MINUS) Vd: Select job from emp where deptno = 10 Union Select job from emp where deptno = 30;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 36
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL JOB --------- CLERK MANAGER PRESIDENT SALESMAN7.6 Bµi tËp1. HiÓn thÞ toµn bé tªn nh©n viªn vµ tªn phßng ban lµm viÖc s¾p xÕp theo tªn phßng ban.2. HiÓn thÞ tªn nh©n viªn, vÞ trÝ ®Þa lý, tªn phßng víi ®iÒu kiÖn l−¬ng >1500. ENAME LOC DNAME ---------- ------------- ----------- KING NEW YORK ACCOUNTING BLAKE CHICAGO SALES CLARK NEW YORK ACCOUNTING JONES DALLAS RESEARCH ALLEN CHICAGO SALES FORD DALLAS RESEARCH SCOTT DALLAS RESEARCH3. HiÓn thÞ tªn nh©n viªn, nghÒ nghiÖp, l−¬ng vµ møc l−¬ng. ENAME JOB SAL GRADE ---------- --------- ---------- ---------- JAMES CLERK 950 1 SMITH CLERK 800 1 ADAMS CLERK 1100 1 MARTIN SALESMAN 1250 2 WARD SALESMAN 1250 2 MILLER CLERK 1300 2 ALLEN SALESMAN 1600 3 TURNER SALESMAN 1500 3 BLAKE MANAGER 2850 4 CLARK MANAGER 2450 4 JONES MANAGER 2975 4 FORD ANALYST 3000 4 SCOTT ANALYST 3000 4 KING PRESIDENT 5000 54. HiÓn thÞ tªn nh©n viªn, nghÒ nghiÖp, l−¬ng vµ møc l−¬ng, víi ®iÒu kiÖn møc l−¬ng = 3. ENAME JOB SAL GRADE ---------- --------- ---------- ---------- ALLEN SALESMAN 1600 3 TURNER SALESMAN 1500 35. HiÓn thÞ nh÷ng nh©n viªn t¹i DALLAS ENAME LOC SAL ---------- ------------- ---------- JONES DALLAS 2975 FORD DALLAS 3000 SMITH DALLAS 800 SCOTT DALLAS 3000 ADAMS DALLAS 11006. HiÓn thÞ tªn nh©n viªn , nghÒ nghiÖp, l−¬ng, møc l−¬ng, tªn phßng lµm viÖc trõ nh©n viªn cã nghÒ lµ cleckvµ s¾p xÕp theo chiÒu gi¶m. ENAME JOB SAL GRADE DNAME ---------- --------- ---------- ---------- -------------- MARTIN SALESMAN 1250 2 SALES WARD SALESMAN 1250 2 SALES ALLEN SALESMAN 1600 3 SALES TURNER SALESMAN 1500 3 SALES§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 37
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL BLAKE MANAGER 2850 4 SALES CLARK MANAGER 2450 4 ACCOUNTING JONES MANAGER 2975 4 RESEARCH FORD ANALYST 3000 4 RESEARCH SCOTT ANALYST 3000 4 RESEARCH KING PRESIDENT 5000 5 ACCOUNTING7. HiÓn thÞ chi tiÕt vÒ nh÷ng nh©n viªn kiÕm ®−îc 36000 $ 1 n¨m hoÆc nghÒ lµ cleck. (gåm c¸c tr−êng tªn,nghÒ, thu nhËp, m· phßng, tªn phßng, møc l−¬ng) ENAME JOB ANUAL_SAL DNAME GRADE ---------- --------- ---------- -------------- ---------- JAMES CLERK 11400 SALES 1 SMITH CLERK 9600 RESEARCH 1 ADAMS CLERK 13200 RESEARCH 1 MILLER CLERK 15600 ACCOUNTING 2 FORD ANALYST 36000 RESEARCH 4 SCOTT ANALYST 36000 RESEARCH 48. HiÓn thÞ nh÷ng phßng kh«ng cã nh©n viªn nµo lµm viÖc. DEPTNO DNAME LOC ---------- -------------- ------------- 40 OPERATIONS BOSTON9. HiÓn thÞ m· nh©n viªn, tªn nh©n viªn, m· ng−êi qu¶n lý, tªn ng−êi qu¶n lý EMP_NAME EMP_SAL MGR_NAME MGR_SAL ---------- ---------- ---------- ---------- BLAKE 2850 KING 5000 CLARK 2450 KING 5000 JONES 2975 KING 5000 MARTIN 1250 BLAKE 2850 ALLEN 1600 BLAKE 2850 TURNER 1500 BLAKE 2850 JAMES 950 BLAKE 2850 WARD 1250 BLAKE 2850 FORD 3000 JONES 2975 SMITH 800 FORD 3000 SCOTT 3000 JONES 2975 ADAMS 1100 SCOTT 3000 MILLER 1300 CLARK 245010. Nh− c©u 9 hiÓn thÞ thªm th«ng tin vÒ «ng KING. EMP_NAME EMP_SAL MGR_NAME MGR_SAL ---------- ---------- ---------- ---------- KING 5000 BLAKE 2850 KING 5000 CLARK 2450 KING 5000 JONES 2975 KING 5000 MARTIN 1250 BLAKE 2850 ALLEN 1600 BLAKE 2850 TURNER 1500 BLAKE 2850 JAMES 950 BLAKE 2850 WARD 1250 BLAKE 2850 FORD 3000 JONES 2975 SMITH 800 FORD 3000 SCOTT 3000 JONES 2975 ADAMS 1100 SCOTT 3000 MILLER 1300 CLARK 2450 EMP_NAME EMP_SAL MGR_NAME MGR_SAL§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 38
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL ---------- ---------- ---------- ---------- BLAKE 2850 BLAKE 2850 MARTIN 1250 BLAKE 2850 ALLEN 1600 BLAKE 2850 TURNER 1500 BLAKE 2850 JAMES 950 BLAKE 2850 WARD 1250 BLAKE 2850 CLARK 2450 CLARK 2450 MILLER 1300 CLARK 2450 JONES 2975 JONES 2975 FORD 3000 JONES 2975 SMITH 800 JONES 2975 SCOTT 3000 JONES 2975 ADAMS 1100 JONES 2975 13 rows selected.11. HiÓn thÞ nghÒ nghiÖp ®−îc tuyÓn dông vµo n¨m 1981 vµ kh«ng ®−îc tuyÓn dông vµo n¨m 1994.12. T×m nh÷ng nh©n viªn gia nhËp c«ng ty tr−íc gi¸m ®èc cña hä.8 C¸c lÖnh truy vÊn lång nhau8.1 C©u lÖnh SELECT lång nhau.Trong mÖnh ®Ò WHERE /T×m nh÷ng nh©n viªn lµm cïng nghÒ víi BLAKE/ select ename, job from emp where job = (select job from emp where ename = ‘BLAKE’); ENAME JOB ---------- -------- BLAKE MANAGER CLARK MANAGER JONES MANAGERTrong mÖnh ®Ò HAVING /T×m nh÷ng phßng cã møc l−¬ng trung b×nh lín h¬n phßng 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 2175To¸n tö SOME/ANY/ALL/NOT IN/EXITSNOT IN : Kh«ng thuécANY vµ SOME : So s¸nh mét gi¸ trÞ víi mçi gi¸ trÞ trong mét danh s¸ch hay trong kÕt qu¶ tr¶ vÒ cña c©u hái con, ph¶i sau to¸n tö =ALL : So s¸nh mét gi¸ trÞ víi mäi gi¸ trÞ trong danh s¸ch hay trong kÕt qu¶ tr¶ vÒ cña c©u hái con.EXISTS : Tr¶ vÒ TRUE nÕu cã tån t¹i. VÝ dô§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 39
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLSELECT * 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, DEPTNOFROM EMPWHERE SAL > SOME ( SELECT DISTINCT SAL FROM EMP WHERE DEPTNO =30)ORDER BY SAL DESC;SELECT EMPNO, ENAME, JOB, DEPTNOFROM EMP EWHERE EXISTS ( SELECT EMPNO FROM EMP WHERE EMP.MGR = E.EMPNO); /T×m nh÷ng ng−êi cã nh©n viªn/8.2 Bµi tËp9 CÊu tróc h×nh c©y9.1 CÊu tróc h×nh c©y trong 1 tableTrong mét table cña CSDL ORACLE cã thÓ hiÖn cÊu tróc h×nh c©y. VÝ dô trong b¶ng EMP cÊu tróc thÓ hiÖncÊp ®é qu¶n lý. KING EMPNO = 7839 Mgr =7839 CLARK JONES BLAKE MILER SCOTT FORD ALLEN WARD MARTIN TUNNER JAMES ADAMS SMITH§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 40
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL• Root node lµ node cÊp cao nhÊt• Child node lµ node con hay kh«ng ph¶i lµ root node• Parent node lµ node cã node con• Leaf node lµ node kh«ng cã node conLevelLevel lµ mét cét gi¶ chøa cÊp ®é trong cÊu tróc h×nh c©y. VÝ dô. SELECT LEVEL, DEPTNO, EMPNO, ENAME, JOB, SAL FROM EMP CONNECT BY PRIOR EMPNO = MGR START WITH MGR is NULL; LEVEL DEPTNO EMPNO ENAME JOB SAL ---------- ---------- ---------- ---------- --------- ---------- 1 10 7839 KING PRESIDENT 5000 2 30 7698 BLAKE MANAGER 2850 3 30 7654 MARTIN SALESMAN 1250 3 30 7499 ALLEN SALESMAN 1600 3 30 7844 TURNER SALESMAN 1500 3 30 7900 JAMES CLERK 950 3 30 7521 WARD SALESMAN 1250 2 10 7782 CLARK MANAGER 2450 3 10 7934 MILLER CLERK 1300 2 20 7566 JONES MANAGER 2975 3 20 7902 FORD ANALYST 3000 4 20 7369 SMITH CLERK 800 3 20 7788 SCOTT SALEMAN 3300 4 20 7876 ADAMS CLERK 11009.2 Kü thuËt thùc hiÖnCã thÓ ®Þnh nghÜa quan hÖ thõa kÕ trong c©u hái b»ng mÖnh ®Ò STAR WITH vµ CONNECT BY trong c©ulªnh SELECT, mçi mÇu tin lµ mét node trong c©y ph©n cÊp. Cét gi¶ LEVEL cho biÕt cÊp cña mÉu tin hay cÊpcña node trong quan hÖ thõa kÕ.Có ph¸p: 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] [ORDER BY expr/position [DESC/ASC]]Trong ®ã:• START WITH §Æc t¶ ®iÓm ®Çu cña h×nh c©y. Kh«ng thÓ ®Ó column gi¶ level ë mÖnh ®Ó nµy.• CONNECT BY ChØ column trong mèi liªn hÖ t×nh c©y.• PRIOR §Þnh h−íng cÊu tróc. NÕu prior xuÊt hiÖn tr−íc mgr, Mgr sÏ ®−îc t×m tr−íc sau ®ã ®Õn empno, ®©y lµ h×nh c©y h−íng lªn. NÕu prior xuÊt hiÖn tr−íc empno, empno sÏ ®−îc t×m tr−íc sau ®ã ®Õn empno, ®©y lµ h×nh c©y h−íng xuèng.VÝ dô SELECT LEVEL, DEPTNO, EMPNO, ENAME, JOB, SAL FROM EMP CONNECT BY PRIOR MGR = EMPNO START WITH empno = 7876;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 41
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL LEVEL DEPTNO EMPNO ENAME JOB SAL ---------- ---------- ---------- ---------- --------- ---------- 1 20 7876 ADAMS CLERK 1100 2 20 7788 SCOTT SALEMAN 3300 3 20 7566 JONES MANAGER 2975 4 10 7839 KING PRESIDENT 5000MÖnh ®Ò WHERE trong cÊu tróc h×nh c©y:MÖnh ®Ò WHERE vµ CONNECT BY cã thÓ ®−îc dïng ®ång thêi trong cÊu tróc h×nh c©y. NÕu mÖnh ®ÒWHERE lo¹i trõ mét sè row cña cÊu tróc h×nh c©y th× chØ nh÷ng row ®ã ®−îc lo¹i trõ. NÕu ®iÒu kiÖn ®Æt trongmÖnh ®Ò CONNECT BY th× toµn bé nh¸nh cña row ®ã bÞ lo¹i 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 DEPTNO EMPNO ENAME JOB SAL ---------- ---------- ---------- ---------- --------- ---------- 1 10 7839 KING PRESIDENT 5000 2 30 7698 BLAKE MANAGER 2850 3 30 7654 MARTIN SALESMAN 1250 3 30 7499 ALLEN SALESMAN 1600 3 30 7844 TURNER SALESMAN 1500 3 30 7900 JAMES CLERK 950 3 30 7521 WARD SALESMAN 1250 2 10 7782 CLARK MANAGER 2450 3 10 7934 MILLER CLERK 1300 2 20 7566 JONES MANAGER 2975 3 20 7902 FORD ANALYST 3000 4 20 7369 SMITH CLERK 800 4 20 7876 ADAMS CLERK 1100 2. SELECT LEVEL, DEPTNO, EMPNO, ENAME, JOB, SAL FROM EMP CONNECT BY PRIOR EMPNO = MGR AND ENAME != ‘SCOTT’ START WITH MGR IS NULL; LEVEL DEPTNO EMPNO ENAME JOB SAL ---------- ---------- ---------- ---------- --------- ---------- 1 10 7839 KING PRESIDENT 5000 2 30 7698 BLAKE MANAGER 2850 3 30 7654 MARTIN SALESMAN 1250 3 30 7499 ALLEN SALESMAN 1600 3 30 7844 TURNER SALESMAN 1500 3 30 7900 JAMES CLERK 950 3 30 7521 WARD SALESMAN 1250 2 10 7782 CLARK MANAGER 2450 3 10 7934 MILLER CLERK 1300 2 20 7566 JONES MANAGER 2975 3 20 7902 FORD ANALYST 3000 4 20 7369 SMITH CLERK 8009.3 Bµi tËp1. T×m tÊt c¶ c¸c nh©n viªn, ngµy gia nhËp c«ng ty, tªn nh©n viªn, tªn ng−êi gi¸m ®èc vµ ngµy gia nhËpc«ng ty cña ng−êi gi¸m ®èc Êy. EMP_NAME EMP_SAL MGR_NAME MGR_SAL ---------- ---------- ---------- ---------- BLAKE 2850 BLAKE 2850 MARTIN 1250 BLAKE 2850 ALLEN 1600 BLAKE 2850 TURNER 1500 BLAKE 2850 JAMES 950 BLAKE 2850§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 42
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL WARD 1250 BLAKE 2850 CLARK 2450 CLARK 2450 MILLER 1300 CLARK 2450 JONES 2975 JONES 2975 FORD 3000 JONES 2975 SMITH 800 JONES 2975 SCOTT 3300 JONES 2975 ADAMS 1100 JONES 2975 13 rows selected.2. T×m nh÷ng nh©n viªn kiÕm ®−îc l−¬ng cao nhÊt trong mçi lo¹i nghÒ nghiÖp. JOB MAX(SAL) --------- --------- ANALYST 3000 CLERK 1300 MANAGER 2975 PRESIDENT 5000 SALESMAN 16003. T×m møc l−¬ng cao nhÊt trong mçi phßng ban, s¾p xÕp theo thø tù phßng ban. ENAME JOB DEPTNO SAL ---------- --------- ---------- ---------- KING PRESIDENT 10 5000 SCOTT SALEMAN 20 3300 BLAKE MANAGER 30 28504. T×m nh©n viªn gia nhËp vµo phßng ban sím nhÊt ENAME HIREDATE DEPTNO ---------- ---------- ---------- CLARK 09-06-1981 10 SMITH 17-12-1980 20 ALLEN 20-02-1981 305. HiÓn thÞ nh÷ng nh©n viªn cã møc l−¬ng lín h¬n l−¬ng TB cña phßng ban mµ hä lµm viÖc. EMPNO ENAME SAL DEPTNO ---------- ---------- ---------- ---------- 7839 KING 5000 10 7566 JONES 2975 20 7902 FORD 3000 20 7788 SCOTT 3300 20 7698 BLAKE 2850 30 7499 ALLEN 1600 306. HiÓn thÞ tªn nh©n viªn, m· nh©n viªn, m· gi¸m ®èc, tªn gi¸m ®èc, phßng ban lµm viÖc cña gi¸m ®èc, møcl−¬ng cña gi¸m ®èc. EMP_NUMBER EMP_NAME EMP_SAL MGR_NUMBER MGR_NAME MGR_DEPT MGR_GRADE ---------- --------------- ---------- ---------- ---------- ---------- 7698 BLAKE 2850 7698 BLAKE 30 4 7654 MARTIN 1250 7698 BLAKE 30 4 7499 ALLEN 1600 7698 BLAKE 30 4 7844 TURNER 1500 7698 BLAKE 30 4 7900 JAMES 950 7698 BLAKE 30 4 7521 WARD 1250 7698 BLAKE 30 4 7782 CLARK 2450 7782 CLARK 10 4 7934 MILLER 1300 7782 CLARK 10 4 7566 JONES 2975 7566 JONES 20 4 7902 FORD 3000 7566 JONES 20 4 7369 SMITH 800 7566 JONES 20 4 7788 SCOTT 3300 7566 JONES 20 4 7876 ADAMS 1100 7566 JONES 20 4 13 rows selected.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 43
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL10 Tæng kÕt vÒ lÖnh selectCÊu tróc lÖnh SELECT [DISTINCT/ALL] [expr [c_ias]] FROM [table/view/snapshot] [t_alias] [WHERE condition] [START WITH condition CONNECT BY condition] [GROUP BY expr] [HAVING condition] [UNION/UNION ALL/INTERSET/MINUS select command] [ORDER BY expr/position [DESC/ASC]] [FOR UPDATE OF [column]] [NOTWAIT]C¸c thµnh phÇn trong c©u lÖnh SELECT DISTINCT ChØ chän 1 cho c¸c row gièng nhau trong kÕt qu¶ ALL KÕt xuÊt c¶ c¸c row gièng nhau * Chän tÊt c¶ c¸c column trong table, view... table.*, view.*, snapshot.* Chän tÊt c¶ c¸c cét trong table, view hay snapshot ®−îc chÞ ®Þnh expr Chän c¸c biÓu thøc c_alias Tªn cét trong kÕt qu¶ kÕt xuÊt. table, view, snapshot lµ Tªn table, view hay snapshot subquery C©u hái select con t_alias Tªn cho c¸c table WHERE Chän c¸c row tháa ®iÒu kiÖn trong mÖnh ®Ò WHERE START WITH,CONNECT BY Chän c¸c dßng trong thø tù thõa kÕ GROUP BY Nhãm c¸c dßng cã expr gièng nhau HAVING Chän nh÷ng nhãm tháa ®iÒu kiÖn mÖnh ®Ò HAVING UNION, UNION ALL, INTERSET, MINUS Cho kÕt qu¶ kÕt hîp c¸c to¸n tö tËp hîp ORDER BY XÕp thø t− c¸c row theo expr hay position (trong danh s¸ch select) ASC, DESC TrËt tù xu«i (mÆc nhiªn) hay ng−îc FOR UPDATE Khãa nh÷ng row ®−îc chän, cho biÕt b¹n cã ý ®Þnh xãa hay cËp nhËt c¸c row nµy NOTWAIT Tr¶ quyÒn ®iÒu khiÓn nÕu khi muèn lock row ®· bÞ lock bëi user kh¸c.11 T¹o table11.1 LÖnh t¹o b¶ng§Ó t¹o mét b¶ng míi dïng lÖnh CREATE TABLE, Có ph¸p nh− sau: CREATE TABLE tablename (column [datatype][DEFAULT expr][column_constraint]..) [table_constraint]) [PCTFREE integer][PCTUSED integer] [INITRANS integer][MAXTRANS integer] [TABLESPACE tablespace] [STORAGE storage_clause] [AS subquery]Trong ®ã: tablename : Tªn table cÇn t¹o column : Tªn column trong table [datatype] : KiÓu d÷ liÖu cña column [DEFAULT expr] : Gi¸ trÞ mÆc ®Þnh cña column trong tr−êng hîp NULL lµ expr [column_constraint] : Rµng buéc cña b¶n th©n column [table_constraint] : rµng buéc cña toµn b¶ng [PCTFREE integer] : % trèng [PCTUSED integer] : % sö dông [INITRANS integer] : Sè b¶n ghi khëi t¹o [MAXTRANS integer] : Sè b¶n ghi lín nhÊt§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 44
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL [TABLESPACE tablespace] : ChØ ®Þnh TABLESAPCE cho b¶ng [STORAGE storage_clause] : Ghi mÖnh ®Ò l−u tr÷, ®¬n vÞ mÆc ®Þnh lµ KB trong ®ã c¸c c¸c chän lùa lµ: INITIAL - dung l−îng khëi t¹o; NEXT - dung l−îng t¨ng tiÕp theo; MINEXTENTS - % më réng nhá nhÊt; MAXEXTENTS- % më réng lín nhÊt; PCTINCREASE - Tèc ®é t¨ng hµng n¨m. [AS subquery] : t¹o b¶ng cã cÊu tróc gièng mÖnh ®Ò truy vÊnVÝ 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 75VÝ du 2 CREATE TABLE SALGRADE1 (GRADE NUMBER CONSTRAINT PK_SALGRADE PRIMARY KEY, LOSAL NUMBER, HISAL NUMBER) TABLESPACE USER STORAGE (INITIAL 6144 NEXT 6144 MINEXTENTS 1 MAXEXTENTS 5 PCTINCREASE 5)VÝ dô 3 CREATE TABLE DEPT10 AS SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE DEPTNO =10;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 ;§Ó t¹o mét table míi, chóng ta cÇn ph¶i chuÈn bÞ mét sè th«ng tin sau:• Table ph¶i ®−îc chuÈn hãa.• Nh÷ng column mµ cho phÐp null nªn ®Þnh nghÜa sau ®Ó tiÕt kiÖm n¬i l−u tr÷.• Gép c¸c table l¹i nÕu cã thÓ.• ChØ ®Þnh c¸c th«ng sè pcfree vµ pctused• Cã thÓ chØ ®Þnh 2 th«ng sè initstran, maxtrans• Cã thÓ chØ ®Þnh tablespace cho table• Cã thÓ −íc l−îng kÝch th−íc table, vµ c¸c th«ng sè cho storage.TÝnh to¸n kÝch th−íc table (tham kh¶o):§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 45
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL1. TÝnh to¸n kho¶ng ®Üa cÇn thiÕt cho data block header. TÝnh theo c«ng thøc sau: BLOCK HEADER = (FIXED HEADER + VARIABLE TRANSACTION HEADER) + ( TABLE DIRECTORY + ROW DIRECTORY) Trong ®ã: fixed header = 57 bytes variable transaction header = 23*gi¸ trÞ cña th«ng sè instrans table directory =4 row directory = 2* sè l−îng row trong block.2. TÝnh to¸n kho¶ng ®Üa trèng ®Ó chøa d÷ liÖu cña data block. TÝnh theo c«ng thøc sau: Kho¶ng ®Üa trèng ®Ó chøa data = (block size -total block header) - (block size -(fixed header+ variable transaction header))*(pctree/100) Cã thÓ biÕt block size b»ng c¸ch dïng lÖnh show parameters db_block_size.3. TÝnh to¸n kho¶ng ®Üa trèng kÕt hîp b»ng gi¸ trÞ cña mçi row.4. TÝnh to¸n kÝch th−íc trung b×nh cña row: KÝch th−íc trung b×nh cña row = row header +A+B+C A = Tæng chiÒu dµi cña c¸c cét <= 250 byte B = Tæng chiÒu dµi cña c¸c cét > 250 byte C = Kho¶ng ®Üa trèng kÕt hîp5. QuyÕt ®Þnh sè row trung b×nh cho mét block: avg rows /block = available space/average row size6. TÝnh to¸n sè l−îng block Block = sè row / sè row trung b×nh cho mét block11.2 C¸c quy t¾c ®Æt tªn object• Tªn dµi tõ 1 ®Õn 30 ký tù, ngo¹i trõ tªn CSDL kh«ng qu¸ 8 ký tù vµ tªn liªn kÕt cã thÓ dµi ®Õn 128 ký tù• Tªn kh«ng chøa dÊu nh¸y (")• Kh«ng ph©n biÖt ch÷ hoa ch÷ th−êng• Tªn ph¶i b¾t ®Çu b»ng ký tù ch÷ trong bé ký tù cña CSDL• Tªn chØ cã thÓ chøa ký tù sè trong tËp ký tù cña CSDL. Cã thÓ dïng c¸c ký tù _, $, #. ORACLE kh«ng khuyÕn khÝch dïng c¸c ký tù $ vµ #.• Tªn kh«ng ®−îc trïng víi c¸c tõ ®· dïng bëi ORACLE (xemphu lôc 1)• Tªn kh«ng ®−îc c¸ch kho¶ng trèng• Tªn cã thÓ ®Æt trong cÆp dÊu nh¸y kÐp, khi ®ã tªn cã thÓ bao gåm c¸c ký tù bÊt kú, cã thÓ bao gåm kho¶ng trèng, cã thÓ dïng c¸c tõ khãa cña ORACLE, ph©n biÖt ch÷ hoa ch÷ th−êng.• Tªn ph¶i duy nhÊt trong "kh«ng gian tªn" nhÊt ®Þnh. C¸c object thuéc cïng kh«ng gian tªn ph¶i cã tªn kh¸c nhau.C¸c bÝ danh cña cét, bÝ danh b¶ng, tªn ng−êi sö dông, mËt khÈu mÆc dï kh«ng ph¶i lµ c¸c object hoÆc c¸cthµnh phÇn con cña object nh−ng còng ph¶i ®−îc ®Æt tªn theo c¸c quy t¾c trªn, ngo¹i trõBÝ danh cét, bÝ danh b¶ng chØ tån t¹i khi thùc hiÖn c¸c lÖnh SQL vµ kh«ng ®−îc l−u tr÷ trong CSDL, do vËykh«ng ¸p dông quy t¾c 9 vÒ kh«ng gian tªn.MËt khÈu kh«ng thuéc vÒ kh«ng gian tªn nµo vµ do ®ã còng kh«ng ¸p dông quy t¾c 9.Nªn ®Æt tªn theo mét quy t¾c ®Æt tªn thèng nhÊt§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 46
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL11.3 C¸c quy t¾c khi tham chiÕu ®Õn objectCó ph¸p chung khi tham chiÕu ®Õn c¸c objectS¬ ®å chung khi tham chiÕu c¸c object hoÆc thµnh phÇn cña c¸c objectSchema.Object.Part.@dblinkTrong ®ã object Tªn object schema Schema chøa object part Thµnh phÇn cña object dblink Tªn CSDL chøa objectORACLE gi¶i quyÕt viÖc tham chiÕu c¸c objectKhi tham chiÕu ®Õn mét object trong c©u lÖnh SQL, ORACLE ph©n tÝch c©u lÖnh vµ vµ x¸c ®Þnh c¸c objecttrong kh«ng gian tªn. Sau khi x¸c ®Þnh c¸c object, ORACLE thùc hiÖn c¸c thao t¸c mµ c©u lÖnh quy ®Þnhtrªn object. NÕu tªn object truy cËp kh«ng thuéc kh«ng gian tªn th× c©u lÖnh kh«ng ®−îc thùc hiÖn vµ cãth«ng b¸o lçi.C©u lÖnh sau thªm mét mÈu tin vµo b¶ng DEPTINSERT INTO Dept VALUES (50, SUPPOR, PARIS)Theo ng÷ c¶nh cña c©u lÖnh, ORACLE x¸c ®Þnh b¶ng Dept cã thÓ lµ• Mét table trong schema cña b¹n• Mét view trong schema cña b¹n• §ång nghÜa riªng cho table hoÆc view• §ång nghÜa chung cho table hoÆc viewTham chiÕu ®Õn c¸c object kh«ng thuéc quyÒn së h÷u§Ó tham chiÕu ®Õn c¸c object kh«ng thuéc schema hiÖn thêi, ph¶i chØ ra tªn cña schema chøa object muèntruy cËpschema.objectVÝ dô ®Ó xãa table EMP trong schema SCOTTDROP TABLE scott.empTham chiÕu c¸c object tõ xa§Ó truy cËp ®Õn mét CSDL ë xa, sau tªn object ph¶i chØ ra tªn liªn kÕt CSDL (database link) cña CSDL chøaobject muèn truy cËp. Database link lµ mét schema object, ORACLE dïng ®Ó th©m nhËp vµ truy xuÊt CSDLtõ xa.11.4 KiÓu d÷ liÖu vµ ®iÒu kiÖn11.4.1 CHARKiÓu CHAR dïng ®Ó khai b¸o mét chuçi cã chiÒu dµi cè ®Þnh, khi khai b¸o biÕn hoÆc cét kiÓu CHAR víichiÒu dµi chØ ®Þnh th× tÊt c¶ c¸c môc tin cña biÕn hay cét nµy ®Òu cã cïng chiÒu dµi ®−îc chØ ®Þnh. C¸c môctin ng¾n h¬n ORACLE sÏ tù ®éng thªm vµo c¸c kho¶ng trèng cho ®ñ chiÒu dµi. ORACLE kh«ng cho phÐp§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 47
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLg¸n môc tin dµi h¬n chiÒu dµi chØ ®Þnh ®èi víi kiÓu CHAR. ChiÒu dµi tèi ®a cho phÐp cña kiÓu CHAR lµ 255byte11.4.2 VARCHAR2KiÓu VARCHAR2 dïng ®Ó khai b¸o chuçi ký tù víi chiÒu dµi thay ®æi. Khi khai b¸o mét biÕn hoÆc cét kiÓuVARCHAR2 ph¶i chØ ra chiÒu dµi tèi ®a, c¸c môc tin chøa trong biÕn hay cét kiÓu VARCHAR2 cã chiÒu dµithùc sù lµ chiÒu dµi cña môc tin. ORACLE kh«ng cho phÐp g¸n môc tin dµi h¬n chiÒu dµi tèi ®a chØ ®Þnh ®èivíi kiÓu VARCHAR2. ChiÒu dµi tèi ®a kiÓu VARCHAR2 lµ 2000 byte11.4.3 VARCHARHiÖn t¹i ORACLE xem kiÓu VARCHAR2 vµ VARCHAR lµ nh− nhau, tuy nhiªn ORACLE khuyªn nªn dïngVARCHAR2. ORACLE dù ®Þnh trong t−¬ng lai dïng kiÓu VARCHAR ®Ó chøa c¸c chuçi víi chiÒu dµi biÕn®æi, nh−ng trong phÐp so s¸nh sÏ ®−îc chØ ®Þnh theo nhiÒu ng÷ nghÜa kh¸c nhau.11.4.4 NUMBERKiÓu sè cña ORACLE dïng ®Ó chøa c¸c môc tin d¹ng sè d−¬ng, sè ©m, sè víi dÊu chÊm ®éng.NUMBER(p, s) trong ®ã p: sè ch÷ sè tr−íc dÊu chÊm thËp ph©n (precision), p tõ 1 ®Õn 38 ch÷ sè s: sè c¸c ch÷ sè tÝnh tõ dÊu chÊm thËp ph©n vÒ bªn ph¶i (scale), s tõ -84 ®Õn 127NUMBER(p) sè cã dÊu chÊm thËp ph©n cè ®Þnh víi precision b»ng p vµ scale b»ng 0NUMBER sè víi dÊu chÊm ®éng víi precision b»ng 38. Nhí r»ng scale kh«ng ®−îc ¸p dông cho sè víi dÊuchÊm ®éng.VÝ dô sau cho thÊy c¸ch thøc ORACLE l−u tr÷ d÷ liÖu kiÓu sè tïy theo c¸ch ®Þnh precision vµ scale kh¸cnhau D÷ liÖu thùc KiÓu L−u tr÷ 7456123.89 NUMBER 7456123.89 7456123.89 NUMBER(9) 7456123 7456123.89 NUMBER(9,2) 7456123.89 7456123.89 NUMBER(9,1) 7456123.8 7456123.89 NUMBER(6) Kh«ng hîp lÖ 7456123.8 NUMBER(15,1) 7456123.8 7456123.89 NUMBER(7,-2) 7456100 7456123.89 NUMBER(-7,2) Kh«ng hîp lÖ11.4.5 FLOATDïng ®Ó khai b¸o kiÓu sè dÊu chÊm ®éng, víi ®é chÝnh x¸c thËp ph©n 38 hay ®é chÝnh x¸c nhÞ ph©n lµ 126.FLOAT(b) Khai b¸o kiÓu dÊu chÊm ®éng víi ®é chÝnh x¸c nhÞ ph©n lµ b, b tõ 1 ®Õn 126. Cã thÓ chuyÓn tõ ®échÝnh x¸c nhÞ phËn sang ®é chÝnh x¸c thËp ph©n b»ng c¸ch nh©n ®é chÝnh x¸c nhÞ ph©n víi 0.30103§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 48
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL11.4.6 LONGDïng ®Ó khai b¸o kiÓu chuçi ký tù víi ®é dµi biÕn ®æi, chiÒu dµi tèi ®a cña kiÓu LONG lµ 2 gigabyte. KiÓuLONG th−êng ®−îc dïng ®Ó chøa c¸c v¨n b¶n.Cã mét sè h¹n chÕ khi dïng kiÓu LONG• Mét table kh«ng thÓ chøa nhiÒu h¬n mét cét kiÓu LONG• D÷ liÖu kiÓu LONG kh«ng thÓ tham gia vµo c¸c rµng buéc toµn vÑn, ngo¹i trõ kiÓm tra NULL vµ kh¸c NULL• Kh«ng thÓ index mét cét kiÓu LONG• Kh«ng thÓ truyÒn tham sè kiÓu LONG cho hµm hoÆc thñ tôc• C¸c hµm kh«ng thÓ tr¶ vÒ d÷ liÖu kiÓu LONG• Trong c©u lÖnh SQL cã truy cËp c¸c cét kiÓu LONG, th× viÖc cËp nhËt hoÆc khãa c¸c b¶ng chØ cho phÐp trong cïng mét CSDLNgoµi ra, c¸c cét kiÓu LONG kh«ng ®−îc tham gia trong c¸c thµnh phÇn sau cña c©u lÖnh SQL• C¸c mÖnh ®Ò WHERE, GROUP BY, ORDER BY, CONNECT BY hoÆc víi t¸c tö DISTINCT trong c©u lÖnh SELECT• C¸c hµm sö dông trong c©u lÖnh SQL nh− SUBSTR, INSTR• Trong danh s¸ch lùa chän cña c©u lÖnh SELECT cã sö dông mÖnh ®Ò GROUP BY• Trong danh s¸ch lùa chän cña c©u hái con, c©u hái cã sö dông c¸c to¸n tö tËp hîp• Trong danh s¸ch lùa chän cña c©u lÖnh CREATE TABLE AS SELECT11.4.7 DATEDïng ®Ó chøa d÷ liÖu ngµy vµ thêi gian. MÆc dï kiÓu ngµy vµ thêi gian cã thÓ ®−îc chøa trong kiÓu CHAR vµNUMBER.Víi gi¸ trÞ kiÓu DATE, nh÷ng th«ng tin ®−îc l−u tr÷ gåm thÕ kû, n¨m, th¸ng, ngµy, giê, phót, gi©y. ORACLEkh«ng cho phÐp g¸n gi¸ trÞ kiÓu ngµy trùc tiÕp, ®Ó g¸n gi¸ trÞ kiÓu ngµy, b¹n ph¶i dïng TO_DATE ®Ó chuyÓngi¸ trÞ kiÓu chuçi ký tù hoÆc kiÓu sè.NÕu g¸n mét gi¸ trÞ kiÓu ngµy mµ kh«ng chØ thêi gian th× thêi gian mÆc ®Þnh lµ 12 giê ®ªm, NÕu g¸n gi¸ trÞkiÓu ngµy mµ kh«ng chØ ra ngµy, th× ngµy mÆc ®Þnh lµ ngµy ®Çu cña th¸ng. Hµm SYSDATE cho biÕt ngµy vµthêi gian hÖ thèng.TÝnh to¸n ®èi víi kiÓu ngµy§èi víi d÷ liÖu kiÓu ngµy, b¹n cã thÓ thùc hiÖn c¸c phÐp to¸n céng vµ trõ.VÝ dôSYSDATE+1 ngµy h«m sauSYSDATE-7 c¸ch ®©y mét tuÇnSYSDATE+(10/1440) m−êi phót sauNgµy Julian: Lµ gi¸ trÞ sè cho biÕt sè ngµy kÓ tõ ngµy 1 th¸ng giªng n¨m 4712 tr−íc c«ng nguyªn.VÝ dô§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 49
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLSELECT TO_CHAR (TO_DATE(01-01-1992, MM-DD-YYYY), J) JULIAN FROM DUALCho kÕt qu¶JULIAN-----------------------------------------------244862311.4.8 RAW vµ LONG RAWKiÓu RAW vµ LONG RAW dïng ®Ó chøa c¸c chuçi byte, c¸c d÷ liÖu nhÞ ph©n nh− h×nh ¶nh, ©m thanh. C¸cd÷ liÖu kiÓu RAW chØ cã thÓ g¸n hoÆc truy cËp chø kh«ng ®−îc thùc hiÖn c¸c thao t¸c nh− ®èi víi chuçi kýtù.KiÓu RAW gièng nh− kiÓu VARCHAR2 vµ kiÓu LONG RAW gièng kiÓu LONG, chØ kh¸c nhau ë chæ ORACLEtù ®éng chuyÓn ®æi c¸c gi¸ trÞ kiÓu CHAR, VARCHAR2 vµ LONG gi÷a tËp hîp ký tù cña CSDL vµ tËp ký tùcña c¸c øng dông.11.4.9 ROWIDMçi mÉu tin trong CSDL cã mét ®Þa chØ cã kiÓu ROWID. ROWID gåmblock.row.file, trong ®ã block : chuçi hÖ hexa cho biÕt block chøa row row : chuçi hÖ hexa cho biÕt row trong block file : chuçi hÖ hexa cho biÕt database file chøa blockVÝ dô 0000000F.0000.0002Row ®Çu tiªn trong block 15 cña data file thø hai.11.4.10 MLSLABELKiÓu MLSLABEL dïng ®Ó chøa label d¹ng nhÞ ph©n mµ ORACLE dïng ®Ó ®¶m b¶o ho¹t ®éng cña b¶n th©nhÖ thèng.11.4.11 ChuyÓn ®æi kiÓuNãi chung mét biÓu thøc kh«ng thÓ gåm c¸c gi¸ trÞ thuéc nhiÒu kiÓu kh¸c nhau, tuy nhiªn ORACLE cho phÐpchuyÓn ®æi gi−· c¸c kiÓu d÷ liÖu. ORACLE tù ®éng chuyÓn kiÓu cña d÷ liÖu trong mét sè tr−êng hîp sau• Khi INSERT hoÆc UPDATE g¸n gi¸ trÞ cho cét cã kiÓu kh¸c, ORACLE sÏ tù ®éng chuyÓn gi¸ trÞ sang kiÓu cña cét.• Khi sö dông c¸c hµm hoÆc c¸c to¸n tö mµ c¸c tham sè cã kiÓu kh«ng t−¬ng thÝch th× ORACLE sÏ tù ®éng chuyÓn kiÓu.• Khi sö dông to¸n tö so s¸nh mµ c¸c gi¸ trÞ cã c¸c kiÓu kh¸c nhau, ORACLE sÏ tù ®éng chuyÓn kiÓu.VÝ dô 1 SELECT ename FROM emp WHERE hiredate = 12-MAR-1993ORACLE ®· tù ®éng chuyÓn chuçi 12-MAR-1993 sang kiÓu DATE trong phÐp so s¸nhVÝ dô 2 SELECT ename FROM emp WHERE ROWID = 00002514.0001.0001§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 50
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLORACLE ®· tù ®éng chuyÓn chuçi 00002514.0001.0001 sang kiÓu ROWID trong phÐp so s¸nhNg−êi sö dông tù chuyÓn ®æiORACLE cung cÊp c¸c hµm ®Ó chuyÓn ®æi kiÓu, vÝ dô• TO_NUMBER ChuyÓn sang kiÓu sè• TO_CHAR ChuyÓn sang kiÓu ký tù• TO_DATE ChuyÓn sang kiÓu ngµy(xem phÇn tra cøu c¸c hµm vµ thñ tôc)11.5 ConstraintC¸c d¹ng constraint gåm: - NULL/NOT NULL - UNIQUE - PRIMARY KEY - FOREIGN KEY ( Referential ) - CHECKNULL/NOT NULL: rµng buéc column trèng hoÆc kh«ng trèng, trong vÝ dô mÖnh ®Ò rµng buéc: CREATE TABLE DEPT ( DEPTNO NUMBER(2) NOT NULL, DNAME CHAR(14), LOC CHAR(13), CONSTRAINT DEPT_PRIMARY_KEY PRIMARY KEY (DEPTNO));UNIQUE: ChØ ra rµng buéc duy nhÊt, c¸c gi¸ trÞ cña column chØ trong mÖnh ®Ò UNIQUE trong c¸c row cñatable ph¶i cã gi¸ trÞ kh¸c biÖt. Gi¸ trÞ null lµ cho phÐp nªu UNIQUE dùa trªn mét cét. Vd: CREATE TABLE DEPT ( DEPTNO NUMBER(2), DNAME CHAR(14), LOC CHAR(13), CONSTRAINT UNQ_DEPT_LOC UNIQUE(DNAME, LOC));PRIMARY KEY: ChØ ra rµng buéc duy nhÊt (gièng UNIQUE), tuy nhiªn kho¸ lµ d¹ng kho¸ UNIQUE cÊp caonhÊt. Mét table chØ cã thÓ cã mét PRIMARY KEY. C¸c gi¸ trÞ trong PRIMARY KEY ph¶i NOTT NULL. Có ph¸p khi ®Æt CONSTRAINT ë møc TABLE [CONSTRAINT constraint_name] PRIMARY KEY (column, Column..) Có ph¸p khi ®Æt CONSTRAINT ë møc COLUMN [CONSTRAINT constraint_name] PRIMARY KEYFOREIGN KEY ( Referential ): ChØ ra mèi liªn hÖ rµng buéc tham chiÕu gi÷a table nµy víi table kh¸c, hoÆctrong chÝnh 1 table. Nã chØ ra mèi liªn hÖ cha-con vµ chØ rµng buéc gi÷a FOREIGN KEY b¶ng nµy víiPRIMARY KEY hoÆc UNIQUE Key cña b¶ng kh¸c. VÝ dô quan hÖ gi÷a DEPT vµ EMP th«ng qua tr−êngDEPTNO.Tõ kho¸ ON DELETE CASCADE ®−îc hØ ®Þnh trong d¹ng kho¸ nµy ®Ó chØ khi d÷ liÖu cha bÞ xo¸ (trong b¶ngDEPT) th× d÷ liÖu con còng tù ®éng bÞ xo¸ theo (trong b¶ng EMP).CHECK: Rµng buéc kiÓm 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)),§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 51
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL 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);11.6 Bµi tËp1. T¹o b¶ng PROJECT víi c¸c column ®−îc chØ ra d−íi ®©y, PROJID lµ promary key, vµ P_END_DATE >P_START_DATE. Column name Data Type Size. ------------------------------------ PROJID NUMBER 4 P_DESC VARCHAR2 20 P_START_DATE DATE P_END_DATE DATE BUDGET_AMOUNT NUMBER 7,2 MAX_NO_STAFF NUMBER 22.. T¹o b¶ng ASSIGNMENTS víi c¸c column ®−îc chØ ra d−íi ®©y, ®ång thêi cét PROJID lµ foreign key tíib¶ng PROJECT, cét EMPNO lµ foreign key tíi b¶ng EMP. Column name Data Type Size. ------------------------------------------------ PROJID NUMBER 4 NOT NULL EMPNO NUMBER 4 NOT NULL A_START_DATE DATE A_END_DATE DATE BILL_AMOUNT NUMBER 4,2 ASSIGN_TYPE VARCHAR2 212 c¸c lÖnh DDL kh¸c vµ d÷ liÖu trong tõ ®iÓn d÷ liÖu12.1 ChØnh söa cÊu tróc tableDïng lÖnh ALTER TABLE ®Ó chØnh söa cÊu tróc b¶ng. Có ph¸p nh− sau: ALTER TABLE tablename [ADD/MODIFY/DROP options ([column [column constraint) [ENABLE clause] [DISABLE clause]Trong ®ã: ADD: thªm column hay constraint. MODIFY: söa ®æi kiÓu c¸c column DROP: bá constraint. ENABLE/DISABLE: Che khuÊt hoÆc ®−a vµo sö dông c¸c CONSTRAINT mµ kh«ng xãa h¼nChó ý:• KhÝ dïng mÖnh ®Ò MODIFY kh«ng thÓ chuyÓn tÝnh chÊt cña COLUMN cã néi dung lµ NULL chuyÓn thµnh NOT NULL;• Kh«ng thÓ ®−a thªm mét cét NOT NUL nÕu table ®· cã sè liÖu. Ph¶i thªm cét NULL, ®iÒn ®Çy sè liÖu, sau ®ã chuyÓn thµnh NOT NULL.• Kh«ng thÓ chuyÓn ®æi kiÓu kh¸c nhau nÕu column ®· chøa sè liÖu• Kh«ng thÓ dïng mÖnh ®Ò MODIFY ®Ó ®Þnh nghÜa c¸c CONSTRAINT trõ rµng buéc NULL/NOT NULL. Muèn söa CONSTRAINT cÇn xo¸ chóng sau ®ã ADD thªm vµo.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 52
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLVÝ 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 emp_mgr; ALTER TABLE DROP PRIMARY KEY;VÝ dô 4 ALTER TABLE dept DISABLE CONSTRAINT dept_prim;12.2 C¸c lÖnh DDL kh¸c12.2.1 Xãa tableDïng lÖnh DROP TABLE ®Ó xo¸ b¶ng. Có ph¸p nh− sau: DROP TABLE table_name [CASCADE CONSTRAINTS]Trong ®ã: Option CASCADE ®Ó xãa tÊt c¶ c¸c rµng buéc toµn vÑn liªn quan ®Õn table bÞ xãa.VÝ dô: DROP TALE empKhi drop table th×:• Xãa tÊt c¶ d÷ liÖu• View vµ synonymliªn quan vÉn cßn nh−ng kh«ng cã gi¸ trÞ• C¸c giao dÞch ch−a gi¶i quyÕt xong sÏ ®−îc commit• ChØ ng−êi t¹o ra table hay DBA míi cã thÓ xãa table12.2.2 Gi¶i thÝch b¶ngDïng lÖnh COMMENT ®Ó chó thÝch. VÝ dô COMMENT ON TABLE EMP IS ‘ THONG TIN NHAN VIEN’; COMMENT ON COLUMN EMP.EMPNO IS ‘ MA SO NHAN VIEN’;12.2.3 Thay ®æi tªn objectDïng lÖnh RENAME ®Ó thay ®æi tªn object. Có ph¸p nh− sau: RENAME old TO newTrong ®ã: Old: Tªn cò New: tªn míiVÝ dô RENAME emp TO employee12.2.4 Xãa d÷ liÖu cña tableDïng lÖnh TRUNCATE TABLE ®Ó xãa d÷ liÖu cña table, xãa tÊt c¶ c¸c row trong table. Có ph¸p nh− sau: TRUNCATE TABLE table_name [REUSE STORAGE]Trong ®ã:§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 53
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL Option REUSE STORAGE gi÷ l¹i khung ®Ó chøa, chØ xãa d÷ liÖu12.3 D÷ liÖu trong tõ ®iÓn d÷ liÖuTrung t©m cña c¬ së d÷ liÖu ORACLE lµ data dictionary. Data dictionary tù ®éng ®−îc t¹o ra khi c¬ së d÷liÖu ORACLE ®−îc t¹o. ORACLE cËp nhËt lªn data dictionary b»ng c¸c lÖnh DDL (Data Define Language).C¸c table cña tõ ®iÓn d÷ liÖu ®−îc t¹o ra b»ng lÖnh CREATE DATABASE vµ chØ ®−îc t¹o tõ user SYS. C¸cview trong tõ ®iÓn d÷ liÖu chøc c¸c th«ng tin d−íi d¹ng dÔ nh×n h¬n b¶ng.Cã c¸c d¹ng view lµ:• USER_xxx: lµ nh÷ng ®èi t−îng thuéc user , vÝ dô c¸c b¶ng ®−îc t¹o bëi user• ALL_xxx: lµ tÊt c¶ c¸c ®èi t−îng mµ user cã quyÒn truy nhËp• DBA_xxx: tÊt c¶ c¸c ®èi t−îng trong database• V$: C¸c thùc thi cña Server.Ngoµi ra cßn cã c¸c view quan träng kh¸c lµ:• DICTIONARY: Th«ng tin vÒ toµn bé c¸c table, view, snapshot trong tõ ®iÓn d÷ liÖu• TABLE_PRIVILEGES: Th«ng tin vÒ viÖc g¸n quyÒn trªn c¸c ®èi t−îng• IND: ®ång nghÜa cña USER_INDEX.Muèn hiÓn thÞ toµn bé th«ng tin vÒ c¸c table, view, snapshot trong tõ ®iÓn d÷ liÖu dïng lÖnh SELECT * FROM DICTIONARY;HiÓn thÞ cÊu cña USER_OBJECT DESCRIBE USER_OBJECT;HiÓn thÞ tÊt c¶ c¸c b¶ng m· user ®ã së h÷u: SELECT OBJECT_NAME FROM USER_OBJECT WHERE OBJECT_TYPE = ‘TABLE’; SELECT * FROM TAB; SELECT TABLE_NAME FROM USER_TABLE;HiÓn thÞ tÊt c¶ c¸c lo¹i ®èi t−îng trong tõ ®iÓn d÷ liÖu: SELECT DISTINCT OBJECT_TYPE FROM USER_OBJECTS;12.4 Bµi tËp1. Thªm column COMMENTS kiÓu LONG vµo b¶ng PROJECTS. Thªm column HOURS kiÓu NUMBERvµo b¶ng ASSIGNMENTS.2. Sö dông view USER_OBJECTS hiÓn thÞ tÊt c¶ c¸c ®èi t−îng user së h÷u.3. Thªm rµng buéc duy nhÊt (UNIQUE) cho 2 column PROJECT_ID vµ EMPNO cña b¶ng ASSIGNMENTS.4. Xem c¸c th«ng tin vÒ c¸c rµng buéc trong USER_CONSTRAINTS.5. Xem trong USER hiÖn t¹i cã tÊt c¶ bao nhiªu b¶ng.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 54
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL13 C¸c lÖnh Thao t¸c d÷ liÖu kh¸c13.1 ChÌn mét row vµo table§Ó chÌn mét row vµo table dïng lÖnh INSERT. Có ph¸p nh− sau: INSERT INTO tablename ([column, column, ...]) VALUES (value, value ...);VÝ dô INSERT INTO dept (depno, dname, loc) VALUES (50, MARKETING, SAN JOSE)ChÐp d÷ liÖu tõ table kh¸c 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 > 100013.2 ChØnh söa d÷ liÖu§Ó chØnh söa d÷ liÖu dïng lÖnh UPDATE. Có ph¸p nh− sau : UPDATE table [alias] SET column [,column...] = [expr, subquery] [WHERE condition]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); Chó thÝch: - CËp nhËt c¸c nh©n viªn ë Dallas hoÆc Detroit - Thay DEPTNO cña c¸c nh©n viªn nµy b»ng DEPTNO cña Boston - Thay l−¬ng cña mçi nh©n viªn b»ng l−¬ng trung b×nh cña bé phËn * 1.1 - Thay commission cña mçi nh©n viªn b»ng commission trung b×nh cña bé phËn * 1.513.3 Xãa dßng§Ó xãa dßng dïng lÖnh DELETE. Có ph¸p nh− sau:§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 55
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL DELETE FROM table [WHERE condition]VÝ dôDELETE FROM emp WHERE deptno = 10;13.4 Lçi rµng buéc d÷ liÖuTh«ng th−êng khi thùc hiÖn c¸c lÖnh thao t¸c d÷ liÖu hay gÆp ph¶i c¸c lçi rµng buéc toµn vÑn d÷ liÖu. C¸c lçinµy xuÊt hiÖn khi cã c¸c rµng buéc tr−íc ®ã mµ d÷ liÖu nhËp vµo, chØnh söa hay khi xo¸ ®i kh«ng ®¶m b¶oc¸c ®iÒu kiÖn toµn vÑn. M· lçi: ORA_02292: INTEGRITY CONSTRAINT Sau ®ã b¸o tªn cña Constraint bÞ lçi.13.5 LÖnh ®iÒu khiÓn giao dÞchMét c©u lÖnh SQL cã thÓ gåm• LÖnh DML thao t¸c d÷ liÖu• LÖnh DDL ®Þnh nghÜa d÷ liÖu• LÖnh DCL ®iÒu khiÓn truy nhËp d÷ liÖuMét giao dÞch b¾t ®Çu khi mét lÖnh SQL ®−îc thùc hiÖnMét giao dÞch kÕt thóc mét trong c¸c tr−êng hîp sau:• COMMIT hoÆc ROLLBACK• C¸c lÖnh DDL vµ DCL thùc hiÖn (tù ®éng commit)• Lçi, tho¸t khái SQL*Plus, hÖ thèng bÞ down.Có ph¸p c¸c lÖnh ®iÒu khiÓn giao dÞch:COMMIT KÕt thóc giao dÞch hiÖn t¹i, thùc hiÖn c¸c chuyÓn ®æi d÷ liÖuSAVEPOINT name X¸c ®Þnh ®iÓm savepoint cña giao dÞchROLLBACK [TO SAVEPOINT name] Quay l¹i d÷ liÖu ë ®iÓm SAVEPOINT hoÆc toµn bé giao dÞch.SET AUTO[COMMIT] ON/OFF Tù ®éng COMMIt khi thùc hiÖn c¸c lÖnh Insert, update, delete. 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 = ‘MARKETING’ WHERE DNAME =’SALES’; COMMIT;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 56
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL13.6 Bµi tËp1. Thªm d÷ liÖu vµo b¶ng PROJECTS. PROJID 1 2 P_DESC WRITE C030 COURSE PROOF READ NOTES P_START_DATE 02-JAN-88 01-JAN-89 P_END_DATE 07-JAN-88 10-JAN-89 BUDGET_AMOUNT 500 600 MAX_NO_STAFF 1 12. Thªm d÷ liÖu vµo b¶ng ASSIGNMENTS. PROJID 1 1 2 EMPNO 7369 7902 7844 A_START_DATE 01-JAN-88 04-JAN-88 01-JAN-89 A_END_DATE 03-JAN-88 07-JAN-88 10-JAN-89 BILL_RATE 50.00 55.00 45.50 ASSIGN_TYPE WR WR PF HOURS 15 20 303. CËp nhËt tr−êng ASIGNMENT_TYPE tõ WT thµnh WR.4. NhËp thªm sè liÖu vµo b¶ng ASSIGNMENTS.14 Sequence vµ index14.1 Sequence14.1.1 T¹o SequenceSequence lµ danh s¸ch tuÇn tù cña con sè, vµ ®−îc t¹o bëi Oracle sever. Sequence dïng ®Ó t¹o khãachÝnh mét c¸ch tù ®éng cho d÷ lÖu.Sequence th−êng dïng ®Ó t¹o khãa chÝnh trong sinh m· tù ®éng. Cã thÓ dïng chung cho nhiÒu ®èi t−îng.Con sè sequence nµy cã chiÒu dµi tèi ®a lµ 38 sè.§Ó t¹o sequence, dïng lÖnh create nh− sau CREATE SEQUENCE sequence_name INCREMENT BY integer START WITH integer [MAXVALUE integer] [MINVALUE integer] [CYCLE/NO CYCLE]; Trong ®ã: INCREMENT BY : chØ ®Þnh kho¶ng c¸ch cña d·y sè tuÇn tù START WITH : ChØ ®Þnh sè ®Çu tiªn cña d·y sè tuÇn tù MAXVALUE : Gi¸ trÞ lín nhÊt cña d·y tuÇn tù MINVALUE : Gi¸ trÞ nhá nhÊt cña d·y tuÇn tù CYCLE/NO CYCLE: D·y tuÇn tù cã quay vßng khi ®Õn ®iÓm cuèi. MÆc ®Þnh lµ NO CYCLEVÝ dô: CREATE SEQUENCE sample_sequence INCREMENT 1 STRAT WITH 2 MAXVALUE 100;§Ó lµm viÖc víi c¸c sequence, dïng lÖnh SQL víi c¸c cét gi¶ sauCURRVAL Cho gi¸ tri hiÖn thêi cña sequenceNEXTVAL T¨ng gi¸ tri hiÖn thêi cña sequence vµ cho gi¸ trÞ sau khi t¨ng ph¶i x¸c ®Þnh tªn sequence tr−íc currval vµ nextval§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 57
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLsequence.CURRVALsequence.NEXTVAL§Ó truy cËp c¸c sequence kh«ng thuéc schema hiÖn thêi, th× ph¶i chØ ra tªn schemaschema.sequence.CURRVALschema.sequence.NEXTVAL§Ó truy cËp c¸c sequence tõ xa, th× cßn ph¶i chØ ra datalinkschema.sequence.CURRVAL@dblinkschema.sequence.NEXTVAL@dblinkSö dông sequenceCURRVAL vµ NEXTVAL cã thÓ ®−îc sö dông trong c¸c tr−êng hîp sau:• Trong danh s¸ch lùa chän cña c©u lÖnh SELECT• Trong mÖnh ®Ò VALUES cña c©u lÖnh INSERT• Trong mÖnh ®Ò SET cña c©u lÖnh UPDATE• Kh«ng ®−îc sö dông CURRVAL vµ NEXTVAL trong c¸c tr−êng hîp sau• Trong c©u hái con• Trong c¸c view vµ snapshot• Trong c©u lÖnh SELECT cã t¸c tö DISTINCT• Trong c©u lÖnh SELECT cã sö dông GROUP BY hay ORDER BY• Trong c©u lÖnh SELECT cã sö dông c¸c phÐp to¸n tËp hîp nh− UNION, INTERSET, MINUS• Trong mÖnh ®Ò WHERE cña c©u lÖnh SELECT• GÝa trÞ DEFAULT cña cét trong c©u lÖnh CREATE TABLE hay ALTER TABLE• Trong ®iÒu kiÖn cña rµng buéc CHECK14.1.2 Xo¸ vµ söa sequenceSöa b»ng lÖnh: ALTER SEQUENCE sequence_name INCREMENT BY integer START WITH integer [MAXVALUE integer] [MINVALUE integer] [CYCLE/NO CYCLE];Xo¸ b»ng lÖnh: DROP SEQUENCE sequence_name ;14.2 IndexIndex lµ mét cÊu tróc c¬ së d÷ liÖu, ®−îc sever sö dông ®Ó t×m mét row trong b¶ng mét c¸ch nhanh chãng.Index bao gåm mét key value ( mét cét (column) trong hµng (row) ) vµ rowid.Có ph¸p: CREATE [UNIQUE]] INDEX index_name ON TABLE ( column [,column...]);§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 58
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL• Dïng index ®Ó query cho nhanh.• Dïng Index khi mµ viÖc lÊy d÷ liÖu <15% sè row trong b¶ng.• Index nh÷ng column nµo dïng ®Ó nèi gi÷a c¸c b¶ng lÉn nhau.• Kh«ng nªn dïng Index cho c¸c b¶ng nµo chØ cã vµi row.• Primaryvµ unique key ( khãa chÝnh vµ khãa duy nhÊt) tù ®éng cã index, nh−ng nªn cã index cho foreign key( khãa ngo¹i).Sè l−îng index cho mét table lµ kh«ng giíi h¹n. Tuy nhiªn nÕu cã qu¸ nhiÒu index sÏ g©y ¶nh h−ëng ®Õn sèliÖu khi mµ d÷ liÖu trong table bÞ thay ®æi thø tù theo index. VÝ dô: Thªm mét row vµo b¶ng tÊt c¶ c¸c IndexsÏ ®−îc update. Nªn chän lùa gi÷a yªu cÇu query, vµ insert, update ®Ó cã mét index hîp lý. §èi víi c¸ckho¸ PRIMARY KEY vµ UNIQUE KEY tõ kho¸ UNIQUE ®−îc tù ®éng thªm khi t¹o INDEX.VÝ dô: CREATE INDEX i-ENAME ON EMP (ENAME);Xo¸ INDEX b»ng lÖnh: DROP INDEX index_name ;14.3 Bµi tËp1. T¹o Index trªn cét PROJID cho b¶ng ASSIGNMENT.2. HiÓn thÞ danh s¸ch cña nh©n viªn thuéc sù qu¶n lý cña ng−êi cã tªn lµ 1 biÕn ®−îc nhËp tõ bµn phÝm EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ---------- ------- ------------- ---------- ----- ------ ---------- 7698 BLAKE MANAGER 7839 01-05-1981 2850 30 7654 MARTIN SALESMAN 7698 28-09-1981 1250 1400 30 7499 ALLEN SALESMAN 7698 20-02-1981 1600 300 30 7844 TURNER SALESMAN 7698 08-09-1981 1500 0 30 7900 JAMES CLERK 7698 03-12-1981 950 30 7521 WARD SALESMAN 7698 22-02-1981 1250 500 3015 T¹o view15.1 ViewView lµ mét table logic, view kh«ng ph¶i lµ n¬i l−u tr÷ d÷ liÖu ë møc vËt lý. C¸c thµnh phÇn cña view dùatrªn table hoÆc lµ trªn view kh¸c. Mäi t¸c ®éng lªn view ®Òu g©y ¶nh h−ëng tíi table cña view ®ã, vµ ng−îcl¹i. §Ó ®Þnh nghÜa mét view dïng query trªn mét b¶ng hay mét view nµo ®ã.Có ph¸p CREATE [OR REPLACE] [FORCE] VIEW view_name [(column, column,...)] AS SELECT statement [WITH CHECK OPTION [CONSTRAINT constraint_name]]; Trong ®ã OR REPLACE : ®Ó t¹o view chÌn lªn view cïng tªn FORCE : ®Ó t¹o view c¶ khi table hay view nµo ®ã kh«ng tån t¹i trong c©u lÖnh SELECT. column, column, :Tªn c¸c column cña view WITH CHECK OPTION : nÕu cã lÖnh insert hoÆc update lªn vie−, ql sÏ kiÓm tra ®iÒu kiÖn phï hîp trong mÖnh ®Ò where cña view. NÕu kh«ng d÷ liÖu sÏ chØ kiÓm tra c¸c rµng buéc toµn vÑn cña b¶ng. CONSTRAINT : chØ ra tªn cña ®iÒu kiÖn kiÓm tra.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 59
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLVÝ dô 1CREATE VIEW emp_viewASSELECT empno, ename, sal FROM emp WHERE deptno = 10;VÝ dô 2CREATE VIEW dept_summary (name, minsal, maxsal, avsal)ASSELECT dname, min(sal), max(sal), avg(sal) FROM emp, deptFROM emp, deptWHERE emp.deptno = dept.deptnoGROUP BY dname;VÝ dô 3CREATE VIEW dept_viewASSELECT eame, sal*12 AnnsalFROM empWHERE deptno = 20WITH CHECK OPTIION CONSTRAINT dept_check;Xãa c¸c viewChØ nh÷ng ng−êi t¹o view míi cã quyÒn DROP DROP VIEW dept_view;View cã thÓ thùc hiÖn c¸c lÖnh SQL sau• Select• Insert (insert trªn view còng ¶nh h−ëng lªn table)• Update (¶nh h−ëng lªn table)• CommentTuy nhiªn cã nh÷ng rµng buéc sau:• Kh«ng thÓ insert, update trªn view, khi query cña view chøa c¸c to¸n tö join, set, distinct, group by, group.• Kh«ng thÓ nµo insert, update trªn view, nÕu nh− trong view cã dïng with check option.• Kh«ng thÓ nµo insert trªn view, trªn table cã nh÷ng cét not Null mµ kh«ng dïng default value ( bëi v× trong tr−êng hîp nµy view sÏ cã Ýt colunm h¬n table table. Nªn insert 1 row vµo view, thùc chÊt lµ insert row ®ã vµo table sÏ kh«ng hîp lÖ).§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 60
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL• Kh«ng thÓ nµo insert trªn view, nÕu view nµy cã dïng biÓu thøc decode.• Nh÷ng query cña view kh«ng thÓ nµo tham kh¶o vµo 2 column gi¶ nextval, currval (nextval, currval dïng cho sequence).15.2 Bµi tËp1. T¹o view cã hiÓn thÞ nh− sau: select * from aggredates; DEPTNO AVERAGE MAXIMUN MINIMUN SUM NO_SALS NO_COMMS ------ ---------- ------- ---------- ---------- ---------- ---------- 10 2916.66667 5000 1300 8750 3 0 20 2235 3300 800 11175 5 0 30 1566.66667 2850 950 9400 6 42. T¹o view ®Ó nhËp sè liÖu vµo b¶ng ASIGNMENT víi c¸c ®iÒu kiÖn sau: PROJID <2000, P_START_DATE<P_END_DATE C¸c gi¸ trÞ cã thÓ chÊp nhËn cña assign_type lµ PS, WT hoÆc ED EMPNO cã gi¸ trÞ NOT NULL BILL_RATE < 50 Víi ASSIGN_TYPE Lµ PS BILL_RATE < 60 Víi ASSIGN_TYPE Lµ WT BILL_RATE < 70 Víi ASSIGN_TYPE Lµ ED2. §Þnh nghÜa b¶ng MESSAGES cã cÊu tróc Column name Data Type --------------------------------------------------- NUMCOL1 NUMBER(9,2) NUMCOL2 NUMBER(9,2) CHARCOL1 VARCHAR2(60) CHARCOL2 VARCHAR2(60) DATECOL1 DATE DATECOL2 DATE16 QuyÒn vµ b¶o mËt16.1 QuyÒn - PRIVILEGEPrivileges lµ c¸c quyÒn h¹n ®−îc thùc hiÖn c¸c thao t¸c hoÆc thùc hiÖn viÖc truy nhËp ®Õn c¸c ®èi t−îng d÷liÖu. Trong Oracle b¹n sÏ kh«ng thÓ thùc hiÖn ®−îc c¸c thao t¸c mµ kh«ng cã c¸c quyÒn t−¬ng øng. C¸cquyÒn h¹n nµy ®−îc g¸n cho User ®Ó cã thÓ thùc hiÖn c¸c thao t¸c trªn c¸c ®èi t−îng chØ ®Þnh. ViÖc g¸nquyÒn ®−îc thùc hiÖn bëi ng−êi qu¶n trÞ c¬ së d÷ liÖu.G¸n quyÒn hoÆc lo¹i bá: §Ó thùc hiÖn g¸n quyÒn cho mét ®èi t−îng dïng lÖnh Grant lo¹i bá quyÒn h¹n dïngRevoke (hoÆc b»ng c¸c c«ng cô hç trî kh¸c nh− Oracle Enterprise manager)C¸c quyÒn bao gåm:• B¶o mËt CSDL • B¶o mËt hÖ thèng • B¶o mËt d÷ liÖu• QuyÒn hÖ thèng: QuyÒn truy nhËp vµ CSDL• QuyÒn trªn ®èi t−îng: Thao t¸c nèi dung cña c¸c ®èi t−îng CSDL• Schema lµ tËp howpjc ¸c ®èi t−îng nh− tables, view...CSDL: Khi cµi ®Æt xong hÖ qu¶n trÞ CSDL ORACLE mÆc ®Þnh ®· cã 2 user.• SYS: Cã quyÒn cao nhÊt. M¹t khÈu lµ change_on_install§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 61
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL• SYSTEM: Cã quyÒn thÊp h¬n SYS. MËt khÈu lµ MANAGERQuyÒn hÖ thèngTrong c¸c quyÒn hÖ thèng quyÒn DBA lµ lín nhÊt. DBA cã quyÒn• CREATE USER : T¹o user míi• DROP USER :Xo¸ user• DROP ANY TABLE :Xo¸ table• BACKUP ANY TABLE :T¹o c¸c backup table.LÖnh t¹o user cña ng−êi cã quyÒn DBA nh− sau: CREATE USER user_name IDENTIFY BY password;QuyÒn trªn ®èi t−îng:• CREATE SESION: Truy nhËp vµo CSDL• CREATE TABLE: t¹o b¶ng trong user ®ã• CREATE SEQUENCE: T¹o sequence• CREATE VIEW: T¹o view• CREATE PROCEDURE: T¹o procedure• ...G¸n quyÒn GRANT privilege[,privilege...] TO user [,user...]Xo¸ quyÒn REVOKE privilege[,privilege...] FROM user [,user...]16.2 ROLERole lµ tªn cña mét nhãm c¸c quyÒn h¹n. Nã ®−îc t¹o ®Ó qu¶n lý quyÒn h¹n cho c¸c øng dông hoÆc nhãmc¸c User. ViÖc dïng role cho phÐp qu¶n lý thèng nhÊt trªn c¸c ®èi t−îng, t¨ng tÝnh mÒm dÎo trong qu¶n trÞ,dÔ dµng thay ®æi. VÝ dô hai ®èi t−îng X, Y cã quyÒn trªn role A tøc lµ role A cã quyÒn g× th× X, Y cã quyÒnt−¬ng øng khi role A bÞ thay ®æi quyÒn h¹n th× X, Y còng bÞ thay ®æi quyÒn h¹n theo.LÖnh t¹o Role: CREATE ROLE role [IDENTIFY BY password];G¸n privilege cho RoleG¸n Role cã c¸c ®èi t−îngMét sè Role hay dïng:• CONNECT• RESOURCELÖnh g¸n vµ xo¸ Role gièng nh− lÖnh g¸n vµ xo¸ Privilege. Chi tiÕt xem trong phÇn qu¶n trÞ ORACLE.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 62
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL16.3 SynonymSynonyms lµ bÝ danh cho mäi ®èi t−îng cña Oracle. C¸c ®èi t−îng cña Oracle lµ table, view, snapshot,sequence, procedure, function, package vµ c¸c synonym kh¸c. Có ph¸p CREATE PUBLIC SYNONYM synonym_name FROM [OWNER.]object_name;Dïng Synonyms cã nh÷ng lîi ®iÓm sau:• Kh«ng tèn thªm n¬i l−u tr÷ kh¸c bëi v× nã ®· ®−îc cÊt trªn tõ ®iÓn d÷ liÖu.• Lµm ®¬n gi¶n ®o¹n ch−¬ng tr×nh SQL.• T¨ng tÝnh b¶o mËt cho database.• Cã thÓ cho phÐp mäi ng−êi (public) truy xuÊt c¸c ®èi t−îng cña Oracle.VÝ dô: Chóng ta cã mét table EMPLY trong schema emp_01Khi lËp tr×nh th× ph¶i truy xuÊt theo emp_01. EMPLY, tªn dµi nh− vËy th× ®o¹n ch−¬ng tr×nh sÏ dµi sÏ dÔ lÇmlÉn. Nªn chóng ta ph¶i dïng synonym CREATE SYNONYM EMP FOR EMP_01.EMPLY;Cã thÓ t¹o mét synonym cho phÐp mäi ng−êi cã thÓ tham kh¶o tíi CREATE PUBLIC EMP FOR EMP_01.EMPLY;TÝnh b¶o mËt lµ v× synonym lµ bÝ danh, nªn ng−êi sö dông dïng bÝ danh nµy sÏ kh«ng ®o¸n ®−îc thªm th«ngtin g×.17 tæng quan vÒ pl/sql vµ procedure builder17.1 Có ph¸p lÖnh PL/SQL• Mçi lÖnh SQL kÒt thóc b»ng dÊu (;)• LÖnh ®Þnh nghÜa CSDL (DDL) kh«ng ®−îc sö dông trong PL/SQL• LÖnh SELECT tr¶ vÒ nhiÒu dßng cã thÓ g©y exception• LÖnh DML cã thÓ t¸c ®éng trªn nhiÒu dßng17.2 PL/SQL blockKhèi lÖnh PL/SQL gåm c¸c thµnh phÇnDECLARE /Kh«ng b¾t buéc/ §Þnh nghÜa c¸c biÕnBEGIN §o¹n lÖnh;EXCEPTION /Kh«ng b¾t buéc/ Hµnh ®ång nÕu lçi xuÊt hiÖn;END;VÝ dô 1DECLARE empno NUMBER(4):=7788;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 63
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLBEGIN UPDATE emp SET sal = 9000 WHERE empno = 0001; ....END;VÝ dô 2DECLARE v_deptno NUMBER(2); v_loc VARCHAR2(15);BEGIN SELECT deptno, loc INTO v_deptno, v_loc FROM dept WHERE dname = SALES;END;17.3 Giíi thiÖu Procedure builderTrong Procedure Builder cã thÓ x©y dùng c¸c ®o¹n ch−¬ng tr×nh PL/SQL nh− program units, libraries, vµdatabase triggers ë c¶ client-side vµ server-side. Procedure Builder cã mét sè thµnh phÇn sau:• Object Navigator lµ phÇn hiÓn thÞ mäi ®èi tîng trong Procedure Builders• Program Unit editor• PL/SQL Interpreter• WizardObject Navigator. §Æc tÝnh• §ãng (+), më (-) c¸c node ®Ó xem th«ng tin• Cã thÓ connect vµo CSDL ®Ó xem th«ng tin vÒ c¸c ®èi t−îng trong CSDL• KÐo th¶ ®Ó copy ®èi t−îng• T×m kiÕm ®èi t−îngProgram Unit editor• T¸c dông: Dïng ®Ó so¹n th¶o ®o¹n ch−¬ng tr×nh PL/SQL dÔ dµng• C¸ch gäi: NhÊn ®óp vµo icon bªn tr¸i cña program unit. HoÆc NhÊn ®óp vµo nót (+) ®Ó t¹o Program unit míi• TiÖn Ých Compile: DÞch§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 64
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL New: T¹o míi Name: T×m theo c¸c program unit Delete: Xo¸ Close: §ãng Help: Trî gióp Apply RevertPL/SQL Interpreter• Khi chän mét program unit nµo ®ã. Néi dung cña program unit sÏ hiÖn lªn cöa sè Interpreter ®Ó debug.• Cöa sè interpreter cßn cã phÇn ®¸nh lÖnh PL/SQL sau dÊu nh¾c PL/SQL>Wizard• Cöa sæ Wizard hiÓn thÞ khi t¹o mét program unit míi b»ng c«ng cô Wizard.• C«ng cô nµy gióp dÔ dµng h¬n trong viÖc x©y dùng c¸c program unit.T¹o mét program unit• T¹o míi b»ng c¸ch nhÊn vµo nót (+) trªn thanh toolbar.• So¹n th¶o Trî gióp so¹n th¶o b»ng menu edit. Cã thÓ dïng import vµ export trªn menu file ®Ó ®−a thªm/lo¹i bá ®o¹n text Chän Syntax palete trong menu program ®Ó trî gióp vÒ có ph¸p Compile ®Ó t×m lçi, th«ng b¸o lçi hiÖn lªn t¹i dßng cuèi cña cöa sèDatabase Trigger• T¹o míi: NhÊn vµo nót (+), chän lo¹i database Trigger• So¹n th¶o: Gièng nh− víi Program unit Thªm c¸c lùa chän thuéc tÝnh cña trigger.T×m vÕt söa lçi c¸c Program Unit• T×m vÕt, söa lçi c¸c Program Unit trong PL/SQL interpreter gåm cã: Toolbar Command line• T¹o c¸c breakpoint (nhÊn ®óp vµo sè dßng lÖnh) ®Ó dõng ®o¹n ch−¬ng tr×nh, kiÓm tra c¸c biÕn runtime, d÷ liÖu...• C¸c c«ng cô trong interpreter Step into: Thùc hiÖn tiÕp ®Õn dßng lÖnh tiÕp theo (cã thÓ ngoµi program unit) Step over: Thùc hiÖn tiÕp ®Õn dßng lÖnh tiÕp theo nh−ng chØ trong Program unit ®ã. Step out: Thùc hiÖn phÇn cßn l¹i cña ch−¬ng tr×nh Go: Thùc hiÖn ®Õn cuèi ch−¬ng tr×nh vµ dõng l¹i khi cã breakpoint§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 65
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL Reset: Bá c¸c breakpoint.Tæ chøc c¸c PL/SQL Program Unit• C¸c PL/SQL Program Unit th−êng ®−îc tæ chøc l¹i trong c¸c library (.PLL/.PPL). Create: T¹o mét library míi Open: Më library Save: Ghi l¹i thay ®æi• Attached library: Sö dông c¸c program unit trong c¸c Attached library nh− c¸c hµm mÆc ®Þnh.• Stored Program Unit: CÊt Program Unit thµnh c¸c Stored Program Unit trong CSDL18 có ph¸p lËp tr×nh18.1 IF IF condition THEN actions [ELSIF condition THEN actions] [ELSE actions] END IFVÝ dô 1IF ename := SCOTT THEN beam_me_up := YES; COMMIT;ELSE beam_me_up := NO; ROLLBACK;END IF;VÝ dô 2IF choice= 1 THEN action := Run payroll; ELSIF choice=2 THEN action:=Run; ELSIF choice=3 THEN action:=Backup; ELSE action:=Invalid;END IF;18.2 LOOP vµ EXIT LOOP actions; [EXIT loop_label [WHEN condition]] END LOOPVÝ dô 1:LOOP counter:=counter-1 INSERT INTO numbered_rows VALUES (counter); ..... IF counter = 10 THEN§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 66
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL COMMIT; EXIT; END IF;END LOOP;VÝ dô 2:LOOP ..... EXIT WHEN total_sals = 60000; ....END LOOP;18.3 FOR FOR control_variable IN [REVERSE] low_value .. high_valueVÝ dôFOR I IN 1..2000LOOP INSERT INTO numbered_rows VALUES (i); preserve_i:=i; ....END LOOP;18.4 WHILE WHILE conditionVÝ dôWHILE Bill<250LOOP actions;END LOOP;18.5 GOTO GOTO labelVÝ dôBEGIN<<label1>>.....GOTO label1§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 67
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL19 cursor19.1 §Þnh nghÜaCursor: lµ kiÓu biÕn cã cÊu tróc, cho phÐp ta xö lý d÷ liÖu gåm nhiÒu dßng. Sè dßng phô thuéc vµo c©u lÖnhquery sau nã. Trong qu¸ tr×nh xö lý cursor nh− lµ mét con trá vÞ trÝ cña row ®ang xö lýC¸c b−íc sö dông biÕn cursor: Khai b¸o -> më -> lÊy d÷ liÖu ®Ó xö lý -> ®ãngKhai b¸o cursor <ten( danh s¸ch biÕn)> is <c©u lÖnh select>: Më vïng d÷ liÖu cÊt tr÷ th«ng tin xö lý. vd: cursor x is select deptno from dept where deptno=10; vd: cursor x(b number) is select * from dept where deptno>b;Më cursor open <ten (trÞ cña biÕn)> vd: open x; vd: open x(10);LÊy d÷ liÖu Fetch <tªn cursor> into <tªn biÕn> Vd: fetch x into b;§ãng cursor Close <tªn cursor> vd: Close x;C¸c thuéc tÝnh %isopen : tr¶ l¹i gi¸ trÞ True nÕu cursor ®ang më %notfound : tr¶ l¹i gi¸ trÞ True nÕu lÖnh fetch hiÖn thêi tr¶ l¹i kh«ng cã row %found : tr¶ l¹i gi¸ tri true cho ®Õn khi fetch kh«ng cßn row nµo %rowcount : tr¶ l¹i sè row ®· ®−îc thùc hiÖn b»ng lÖnh fetchVÝ dô1: declare cursor v_a is select * from emp; m v_a%rowtype; begin open v_a; loop fetch v_a into m; insert into t_thu(empno, ename,job) values (m.empno,m.ename, m.job); exit when v_a%notfound; end loop; close v_a; end;vÝ dô 2:DECLARE CURSOR c1 IS SELECT dname, loc FROM dept FOR UPDATE OF loc; dept_rec c1%ROWTYPE; sales_count NUMBER:=0; non_sales NUMBER:=0;§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 68
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLBEGIN OPEN c1; LOOP FETCH c1 INTO dept_rec; EXIT WHEN c1%NOTFOUND; IF dept_rec.dname = SALES AND dept_rec.loc!=DALLAS THEN UPDATE dept SET loc=DALLAS WHERE CURRENT OF c1; sales_count:=sales_count+1; ELSIF dept rec.dname!=SALES AND dept_rec.loc!=NEWYORK THEN UPDATE dept SET loc =NEWYORK WHERE CURRENT OF c1; non_sales:=non_sales+1; END IF; END LOOP; CLOSE c1; INSERT INTO counts (sales_set, non_sales_set) VALUES (sales_count, non_sales); COMMIT;END;19.2 KiÓu d÷ liÖu Table vµ RecordKiÓu d÷ liÖu TableCó ph¸p: TYPE type_name IS TABLE OF datatype [NOT NULL] INDEX BY BINARY_INTEGER; var type_name;VÝ dô TYPE NAME IS TABLE OF EMP.ENAME%TYPE; First_name NAME; Last_name NAME;KiÓu d÷ liÖu RecordCó ph¸p TYPE type_name IS RECORD OF (Col1 datatype [NOT NULL{:=|DEFAULT} expr], (Col2 datatype [NOT NULL{:=|DEFAULT} expr]...); var type_name;VÝ dô§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 69
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL TYPE emp_rec IS RECORD OF empno number(4) not null, ename char(10), job char(9), mgr number(4), hiredate date default sysdate, sal number(7,2), comm number(7,2), deptno number(2) not null ); Emp_record emp_rec;19.3 Sao kiÓu d÷ liÖuB¶n ghi trong PL/SQL. lµ mét biÕn cã thÓ gi÷ nhiÒu gi¸ trÞ vµ lµ mét tËp hîp c¸c biÕn t−¬ng øng víi c¸ctr−êng trong table.§Ó ®Þnh nghÜa kiÓu d÷ liÖu b¶n ghi. Var varref%ROWTYPE Trong ®ã Var : biÕn b¶n ghi Varref : Tªn b¶ngVÝ dô: X emp%ROWTYPE;§Ó truy nhËp ®Õn c¸c tr−êng trong d÷ liÖu b¶n ghi dïng gièng nh− trong 1 row. VÝ dô x.empno, x.sal...§Ó sao kiÓu d÷ liÖu cña mét biÕn nµo ®ã. X salgade%TYPE X sÏ cã kiÓu d÷ liÖu gièng biÕn salgrade.19.4 C©u lÖnh SELECT... INTO... trong PL/SQLCó ph¸p SELECT col1, col2... INTO var1, var2... [cursor_var] FROM table1, table2... [WHERE condition1, condition2... ] [GROUP BY col1, col2 ...] [HAVING condition1, condition2...] [FOR UPDATE]; trong ®ã: INTO var1, var2... [cursor_var] ®Ó ®−a gi¸ trÞ trong table vµo trong c¸c biÕn ( cã thÓ lµ biÕn cursor ).VÝ dô: SELECT deptno, loc INTO v_deptno, v_loc FROM dept WHERE dname = ‘SALES’;19.5 Bµi tËp1. ViÕt ®o¹n ch−¬ng tr×nh t×m kiÕm c¸c hµng trong b¶ng EMP víi biÕn ®−îc ®−a tõ ngoµi vµo lµ &1 d¹ngJOb_type(emp.job%type)vµ ®−a ra th«ng b¸o thÝch hîp vµo b¶ng MESSAGES.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 70
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL2. ViÕt ®o¹n ch−¬ng tr×nh ghi d÷ liÖu vµo b¶ng MESSAGES víi cét NUMCOL1 mang gi¸ trÞ lµ 1 nÕu lµ row 1®−îc Insert, 2 nÕu row 2 ®−îc Insert.... Kh«ng ®−îc Insert nh÷ng row cã gi¸ trÞ lµ 6 hoÆc 8, tho¸t khái vßnglÆp insert sau gi¸ trÞ 10. Commit sau vßng lÆp.3. LiÖt kª c¸c cét ENAME, HIREDATE, SAL Víi ®iÒu kiÖn EMPNO b»ng gi¸ trÞ biÕn &EMPLOYEE_NO ®−îc®−a vµo, sau ®ã kiÓm tra - Cã ph¶i møc l−¬ng lín h¬n 1200 - Tªn nh©n viªn cã ph¶i cã chøa ch÷ T - ngµy gia nhËp c¬ quan cã ph¶i lµ th¸ng 10 (DEC)vµ ®−a gi¸ trÞ kiÓm tra nµy vµo b¶ng message cét charcol1 (thö víi c¸c gi¸ trÞ 7654, 7369, 7900, 7876)4. §−a vµo vßng lÆp v tõ 1 ®Õn 10 lÖnh UPDATE messages SET numcol2=100 WHERE numcol1 = v;nÕu bÊt kú mét lÇn update nµo ®ã cã sè l−îng row >1 th× exit khái vßng lÆp.20 procedure vµ funtion20.1 ProcedureLµ mét nhãm c¸c lÖnh thùc hiÖn chøc n¨ng nµo ®ã nh»m t¨ng kh¶ n¨ng xö lý, kh¶ n¨ng sö dông c¸c thñ tôcchung, t¨ng tÝnh b¶o mËt vµ an toµn d÷ liÖu, tiÖn Ých trong ph¸t triÓn.Có ph¸p:Procedure : Lµ tªn cña procedure ®−îc t¹o.Argument : Gåm tªn cña danh s¸ch c¸c biÕn vµ kiÓu cña nã.IN : ChØ ®Þnh r»ng b¹n ph¶i ®−a trÞ khi gäi procedure.OUT : ChØ ra r»ng Procedure sÏ tr¶ l¹i trÞ cho biÕn tíi m«i tr−êng gäi nã.IN OUT : ChØ ra r»ng b¹n ph¶i g¸n trÞ cho argument khi gäi procedure vµ procedure sÏ tr¶ l¹i trÞargument tíi m«i tr−êng gäi.NÕu kh«ng ghi IN, OUT hoÆc IN OUT th× ngÇm ®Þnh sÏ lµ IN§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 71
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLDatatype : Lµ kiÓu cña argument, ë ®©y chØ ®−îc khai b¸o kiÓu mµ kg«ng ®−îc khai b¸o c¸c chiÒu dµiargument. VÝ dô kh«ng ®−îc khai b¸o argument lµ VARCHAR2(10) mµ ph¶i khai b¸o lµ VARCHAR2.Pl/sql_subprogram_body: Lµ phÇn th©n cña procedure ®−îc viÕt b»ng PL/SQL.VÝ dô: CREATE OR REPLACE PROCEDURE INS_DEPT(X NUMBER, Y VARCHAR2) IS BEGIN INSERT INTO DEPT(DEPTNO,DNAME) VALUES (X,Y); END;Muèn thùc hiÖn procedure t¹i SQL plus thù hiÖn dïng lÖnh execute <ten(danh s¸ch gi¸ trÞ). Cßn trong c¸cthñ tôc kh¸c dïng lÖnh gäi b×nh th−êng SQL> execute ins_dept(55,’ New Name’);20.2 FunctionCó ph¸p:C¸c tham gièng nh− procedure nh−ng kh¸c lµ sau khi gäi hµm tr¶ l¹i trÞVÝ dô: create or replace function get_dname( y number) return varchar2 is m char(14); begin select dname into m from dept where deptno=y; if SQL%notfound then m:=Khong thay; end if; return(rtrim(m)); end;§Ó gäi hµm get_dname ta gäi trùc tiÕp hoÆc th«ng qua c¸c phÐp g¸n.VÝ dô: SQL> select * from dept where dname=get_dname(10); DEPTNO DNAME LOC --------- -------------- ------------- 10 ACCOUNTING NEW YORK SQL> select get_dname(20) from dual; GET_DNAME(20) --------------------------------------------------------§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 72
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL RESEARCH20.3 Bµi tËp1. ViÕt hµm lÊy tªn gi¸m ®èc theo biÕn empno ®−îc nhËp vµo,2. ViÕt thñ tôc nhËp th«ng tin vµo b¶ng message c¸c tr−êng numcol1: M· phßng charcol1: tªn phßng ban numcol2: tæng l−¬ng cña phßng3. ViÕt thñ tôc dïng cursor; lÊy sè liÖu vÒ n ng−êi (n lµ mét biÕn ®−îc ®−a vµo tõ man h×nh) cã møc l−¬ngcao nhÊt trong b¶ng emp ®−a vµo b¶ng top_sal víi c¸c gi¸ trÞ t−¬ng øng trong num=empno, name = ename,salary = sal). B¶ng top_sal cã cÊu tróc nh− sau: NUM NUMBER(4) NAME VARCHAR2(25) SALARY NUMBER(11,2)21 pakage21.1 PackageLµ tËp hîp cña c¸c ®èi t−îng gåm c¸c procedure, function, variable, constant, cursor vµ c¸c exception.ViÖc t¹o c¸c package cho phÐp t¨ng kh¶ n¨ng mÒm dÎo, t¨ng tÝnh b¶o mËt, t¹o sù thuËn lîi trong viÖc qu¶nlý hÖ thèng ®ång thêi t¨ng hiÖu suÊt xö lý cña hÖ thèng.§Ó t¹o package thùc hiÖn nh− sau:§Ó t¹o package body thùc hiÖn nh− sau:Víi c¸c releases tr−íc ®©y cña PL/SQL viÖc gäi c¸c functions chØ cã thÓ ®−îc thùc hiÖn b»ng c¸c lÖnh cñaprocedure, nh−ng giê th× c¸c lêi gäi nµy cã thÓ xuÊt hiÖn trong c©u lÖnh SQL gièng nh− lÖnh procedure. §iÒunµy cã nghÜa lµ ta cã thÓ sö dông c¸c functions gièng nh− c¸c built-in SQL functions. B»ng c¸c më réng SQLta cã thÓ tËp hîp ph©n tÝch ngay bªn trong Oracle Server mµ ta kh«ng cÇn lÊy d÷ liÖu vµo trong øng dông®iÒu nµy lµm t¨ng tÝnh ®éc lËp cña c¬ së d÷ liÖu.Tuy nhiªn ®Ó cã thÓ gäi ®−îc tõ SQL th× c¸c function ph¶i ®¶m b¶o ch¾c ch¾n viÖc kiÓm so¸t kÕt qu¶. Víic¸c standalone functions th× Oracle cã thÓ thùc hiÖn ®iÒu nµy b»ng viÖc kiÓm tra function body. Tuy nhiªn víibody cña package lµ Èn cho nªn c¸c packaged functions ta ph¶i sö dông pragmaRESTRICT_REFERENCES ®Ó ®¶m b¶o luËt nµy.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 73
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL Pragma Restrict_references(<Function/procedure Name>, <var1>, ...) Trong ®ã: WNDS: Write no database state RNDS: Read no database state WNPS: Write no package state RNPS: Read no package stateVÝ dô: create or replace package vidu is function get_dname( y number) return varchar2; Pragma Resctrict_references(get_dname, WNDS, WNPS); Procedure ins_dept (x number, y varchar2); end vidu; create or replace package body vidu is function get_dname( y number) return varchar2 is m char(14); begin select dname into m from dept where deptno=y; if SQL%notfound then m:=Khong thay; end if; return(rtrim(m)); end; procedure ins_dept(x number, y varchar2) is begin insert into dept(deptno,dname) values (x,y); end; end vidu;§Ó gäi ta thùc hiÖn nh− sau: SQL> execute vidu.ins_dept(70,Vi du);22 database trigger22.1 Database TriggerMét Database Trigger ®−îc t¹o vµ l−u tr÷ trong PL/SQL block t−¬ng øng víi table. Nã ®−îc tù ®éng gäi ®Õnkhi cã sù truy nhËp ®Õn table t−¬ng øng víi c¸c hµnh ®éng ®Þnh nghÜa.§Ó t¹o mét triger ta gâ theo cã ph¸p sau:§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 74
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLCreate or replace : lÖnh t¹o hoÆc t¹o l¹i trigger nÕu nã ®· tån t¹i.Before : ChØ ra r»ng trigger sÏ ®−îc thùc hiÖn tr−íc khi thùc hiÖn lÖnh.Affter : ChØ ra r»ng trigger sÏ ®−îc thùc hiÖn sau lÖnh gäi tíi nã.Delete, Insert, Update of <column> on <table>: trigger sÏ ®−îc gäi khi cã c¸c hµnh ®éng t−¬ng øng trªntõng column cña b¶ng.Referencing : ChØ tªn quan hÖ tíi c¸c trÞ cò (OLD) vµ míi (NEW) cña row .For each row : Trigger thùc hiÖn t−¬ng øng víi mçi row cã ®iÒu kiÖn øng víi mÖnh ®Ò trongWHEN.Pl/sql_block : Lµ khèi lÖnh PL/SQL thùc hiÖn c¸c xö lý theo mong muèn.VÝ dô: create or replace trigger t_dname before insert or update of dname on dept for each row when (new.dname is null) begin if (:new.dname is null) then :new.dname:=No Name; end if; end ;22.2 Bµi tËp1. ViÕt trigger ®Ó khi nhËp sè liÖu vµo b¶ng emp th× nã còng nhËp sè liÖu vµo b¶ng emp1 víi ®iÒu kiÖn cÊutróc b¶ng emp1 cã empno, ename, job, dname2. Thªm 1 cét vµo b¶ng DEP tªn lµ SUMSAL. ViÕt trigger ®Ó cét SUMSAL lu«n chøa tæng l−¬ng cña phßngban ®ã ( d÷ liÖu lÊy t−¬ng øng tõ b¶ng emp)3. LËp 1 b¶ng tªn lµ BACKUP cã cÊu tróc gièng b¶ng EMP sao cho mçi b¶n ghi trong emp bÞ xo¸ sÏ l−usang backup4. øng víi c¸c theo t¸c insert, update, delete trªn b¶ng emp, l−u l¹i c¸c theo t¸c ®ã vµo b¶ng message, víid÷ liÖu t−¬ng øng charcol1 = tªn thao t¸c, datecol2 = Ngµy giê thùc hiÖn.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 75
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQL23 error handingError handing lµ lçi xuÊt hiÖn trong khèi lÖnh PL/SQL, tÊt c¶ c¸c lçi nµy sÏ ch¹y vÒ phÇn EXCEPTION trongkhèi lÖnh ®Ó xö lý.Khèi lÖnh PL/SQL gåm c¸c thµnh phÇnDECLARE /Kh«ng b¾t buéc/ §Þnh nghÜa c¸c biÕnBEGIN §o¹n lÖnh;EXCEPTION /Kh«ng b¾t buéc/ Hµnh ®ång nÕu lçi xuÊt hiÖn;END;Có ph¸p thùc hiÖn c¸c EXCEPTION; EXCEPTION WHEN exception1 [OR exception1. . .] THEN Xö lý; . . . [WHEN exception3 [OR exception4. . .] THEN Xö lý; . . .] [WHEN OTHERS THEN Xö lý; . . .] Trong ®ã: exception : tªn lçi n WHEN OTHERS : dïng ®Ó xö lý c¸c tr−êng hîp lçi kh¸c§iÒu kiÖn kÝch ho¹t exceptionCã 2 nhãm exception:• C¸c exception cña b¶n th©n Oracle nh−: NO_DATA_FOUND, FOUND, TOO_MANY_ROW ...• C¸c exception do ng−êi sö dông khai b¸oC¸c exception hÖ thèng tù ®éng bÞ kÝch ho¹t trong c¸c tr−êng hîp nhÊt ®Þnh. C¸c exception ng−êi sö dông®Þnh nghÜa ph¶i tù kÝch ho¹t, vÝ dôRAISE exception_identifier;Mét sè exception hay dïng cña b¶n th©n Oracle:Tªn M· lçi M« t¶NO_DATA_FOUND ORA_01403 C©u lÖnh SELECT INTO kh«ng tr¶ vÒ row nµoTOO_MANY_ROW ORA_01422 C©u lÖnh SELECT INTO kh«ng tr¶ vÒ lín h¬n 1 rowINVALID_CURSOR ORA_01001 Lçi xö lý CURSORZERO_DIVIDE ORA_01476 Lçi chia cho 0§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 76
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLDUP_VAL_ON_INDEX ORA_00001 Lçi gi¸ trÞ bÞ trïng l¾p trong mét UNI QUE INDEXVÝ dô Xo¸ nh÷ng nh©n viªn trong b¶ng emp nÕu t¹i phßng nh©n viªn ®ã lµm viÖc chØ cã mét nh©n viªn; trongProcedure buider PROCEDURE DELEMP (V_EMP IN EMP.EMPNO%TYPE) IS V_ID EMP.EMPNO%TYPE; BEGIN SELECT EMPNO INTO V_ID FROM EMP WHERE EMPNO = V_EMP; DELETE FROM EMP WHERE EMPNO = V_EMP; COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN ROLLBACK; TEXT_IO.PUT_LINE(TO_CHAR(V_EMP)||KHONG CO); WHEN TOO_MANY_ROWS THEN ROLLBACK; TEXT_IO.PUT_LINE(CO LOI DU LIEU TRONG BANG EMP); WHEN OTHERS THEN ROLLBACK; TEXT_IO.PUT_LINE(CO LOI KHAC TRONG BANG EMP); END;Gäi ch¹y delemp(7364);C¸c exception do ng−êi sö dông ®Þnh nghÜaKhai b¸o exception identifier EXCEPTION;VÝ dô:DECLARE credit_exceeded EXCEPTION;BEGIN IF stock_ordered > credit_limit THEN RAISE credit_exceeded; END IF .... EXCEPTION WHEN credit_exceeded THEN ....END;§Æt tªn cho c¸c exception hÖ thèngMçi exception hÖ thèng ®−îc g¸n mét sè x¸c ®Þnh, cã thÓ ®Æt tªn cho c¸c exception ®Ó dÔ sö dông h¬n. PRAGMA EXCEPTION_INIT (exception_identifier, number)§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 77
  • C«ng ty cæ phÇn ®Çu t− ph¸t triÓn c«ng nghÖ - FPT Gi¸o tr×nh SQL vµ PL/SQLVÝ dôDECLARE fetch_failed EXCEPTION; PRAGMA EXCEPTION_INIT (fetch_failed, -1002);BEGIN .... EXCEPTION WHEN fetch_failed THEN ....END;23.1 Bµi tËp1. Dïng EXCEPTION b¾t lçi chÆt h¬n cho c¸c bµi tËp tõ phÇn 19-22.§µo t¹o c¬ b¶n: SQL vµ PL/SQL Trang 78