You are on page 1of 275

Bi ging H qun tr CSDL

MC LC
MC LC .............................................................................................................................1 Chng 1: TNG QUAN V H QUN TR CSDL..........................................................3 1.1. nh ngha: .................................................................................................................3 1.2. Cc kh nng ca h qun tr CSDL...........................................................................3 1.3. c im ca mt h qun tr CSDL..........................................................................4 1.3.1. S tru tng ho d liu: ...................................................................................4 1.3.2. Ngn ng c s d liu........................................................................................5 1.3.3. X l cu hi.......................................................................................................6 1.3.4. Qun tr giao dch ................................................................................................6 1.3.5. Qun l lu tr .....................................................................................................7 1.4. Kin trc ca mt h qun tr CSDL ..........................................................................7 1.5. Cc chc nng ca h qun tr CSDL quan h ...........................................................9 1.5.1. Cc khi nim trong m hnh d liu quan h ....................................................9 1.5.2. Cc chc nng ca h qun tr CSDL quan h ..................................................11 Chng 2: CC CU LNH SQL C BN .....................................................................14 2.1. CC CU LNH NH NGHA D LIU ...........................................................14 2.1.1. Lnh CREATE...................................................................................................14 2.1.2. Lnh thay th sa i ALTER ...........................................................................15 2.1.3. Xo cu trc DROP ...........................................................................................16 2.2. CC CU LNH CP NHT D LIU ...............................................................16 2.2.1. Lnh Insert .........................................................................................................16 2.2.2. Lnh Update.......................................................................................................16 2.2.2. Lnh Delete........................................................................................................17 2.3. KIM SOT D LIU............................................................................................17 2.3.1. Trao quyn GRANT ..........................................................................................17 2.3.2. Thu hi quyn REVOTE ...................................................................................17 2.4. TRUY VN D LIU.............................................................................................18 2.4.1. Tm kim theo cu hi n gin ........................................................................18 2.4.2. S dng cc hm th vin..................................................................................19 2.4.3. Tm kim nh cc mnh ................................................................................20 2.4.4. Cu hi phc tp ................................................................................................21 Chng 3: H QUN TR C S D LIU SQL SERVER ...........................................24 3.1. TNG QUAN V H QUN TR SQL SERVER .................................................24 3.1.1. Gii thiu h qun tr SQL Server .....................................................................24 3.1.2.Cc thnh phn ca SQL Server .........................................................................24 3.1.2.1. Cc thnh phn ca SQL Server 2000 ............................................................24 3.1.2.2. Cc thnh phn ca SQL Server 2005 ............................................................28 3.1.3. Qun l cc dch v ca SQL Server.................................................................32 3.1.3.1. Qun l cc dch v ca SQL Server 2000....................................................32 3.1.3.2. Qun l cc dch v ca SQL Server 2005....................................................36 3.2. LM VIC VI CC I TNG TRONG SQL SERVER............................... 44 3.2.1. C s d liu - Database....................................................................................45 3.2.2.Bng - Table........................................................................................................59 3.2.3. View...................................................................................................................67

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

3.2.4. Ch mc - Index .................................................................................................80 3.2.5. Lc - Diagrams ...........................................................................................92 3.3. BO M D LIU TRONG SQL SERVER.....................................................110 3.3.1. Phn quyn v bo mt trong SQL Server.......................................................110 3.3.2. Sao lu - phc hi CSDL.................................................................................138 Chng 4. LP TRNH TRN SQL SERVER ................................................................152 4.1. Gii thiu ngn ng T-SQL....................................................................................152 4.1.1. Khi nim.........................................................................................................152 4.1.2. Pht biu truy vn d liu nng cao.................................................................152 4.1.3. Lp trnh cu trc trong SQL Server ...............................................................160 4.2. Cc store procedure Cc th tc ..........................................................................179 4.2.1. Khi nim.........................................................................................................179 4.2.2. To store procedure .........................................................................................179 4.2.3.Thay i, xa, xem ni dung store procedure...................................................185 4.3. Cc store function Cc hm .................................................................................187 4.3.1. Cc khi nim ..................................................................................................187 4.3.2. To cc hm .....................................................................................................187 4.3.3. Cc v d to cc hm ......................................................................................189 4.3.4.Thay i, xa, xem ni dung store function .....................................................192 4.4. Trigger ....................................................................................................................193 4.4.1. Khi nim.........................................................................................................193 4.4.2. To trigger........................................................................................................195 4.4.3. Cc thao tc qun l trigger .............................................................................204 Chng 5. SQL SERVER V LP TRNH NG DNG...............................................208 5.1. M hnh kt ni ng dng n SQL server.............................................................208 5.1.1. M hnh ADO .................................................................................................. 208 5.1.2. M hnh ADO.NET .........................................................................................210 5.1.3. im khc nhau gia ADO v ADO.NET ...................................................... 215 5.2. Cc lp SqlClient trong m hnh ADO.NET.......................................................... 215 5.2.1. Class SqlConnection ........................................................................................216 5.2.2. Class SqlCommand..........................................................................................219 5.2.3. Class SqlDataAdapter ......................................................................................224 5.2.4. Class DataSet ...................................................................................................230 5.2.5. DataView .........................................................................................................231 5.3. V d minh ha .......................................................................................................234 5.3.1. CSDL trong v d minh ha.............................................................................235 5.3.2. Xy dng Form nhp DSSinhVien ..................................................................236 5.3.3. Xy dng Form nhp DSLop...........................................................................244 5.3.4. Xy dng Form hin th danh sch sinh vin. .................................................246 5.3.5. Xy dng bo co dng Report. ......................................................................252 5.3.6. Xy dng report dng Crystal Report..............................................................266

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

Chng 1: TNG QUAN V H QUN TR CSDL 1.1. nh ngha: - H qun tr c s d liu (Database Management System - DBMS): L mt h thng phn mm cho php to lp c s d liu v iu khin mi truy nhp i vi c s d liu . Trn th trng phn mm hin nay Vit Nam xut hin kh nhiu phn mm h qun tr c s d liu nh: Microsoft Access, Foxpro, DB2, SQL Server, Oracle,.v.v - H qun tr c s d liu quan h (Relation Database Management System - RDBMS) l mt h qun tr c s d liu theo m hnh quan h. 1.2. Cc kh nng ca h qun tr CSDL C hai kh nng chnh cho php phn bit cc h qun tr c s d liu vi cc kiu h thng lp trnh khc: i. Kh nng qun l d liu tn ti lu di: c im ny ch ra rng c mt c s d liu tn ti trong mt thi gian di, ni dung ca c s d liu ny l cc d liu m h qun tr CSDL truy nhp v qun l. Kh nng truy nhp cc khi lng d liu ln mt cch hiu qu.

ii.

Ngoi hai kh nng c bn trn, h qun tr CSDL cn c cc kh nng khc m c th thy trong hu ht cc h qun tr CSDL l: iii. iv. v. vi. H tr t nht mt m hnh d liu hay mt s tru tng ton hc m qua ngi s dng c th quan st d liu. m bo tnh c lp d liu hay s bt bin ca chng trnh ng dng i vi cc thay i v cu trc trong m hnh d liu. H tr cc ngn ng cao cp nht nh cho php ngi s dng nh ngha cu trc d liu, truy nhp d liu v thao tc d liu. Qun l giao dch, c ngha l kh nng cung cp cc truy nhp ng thi, ng n i vi CSDL t nhiu ngi s dng ti cng mt thi im.
B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

Bi ging H qun tr CSDL

vii.

iu khin truy nhp, c ngha l kh nng hn ch truy nhp n cc d liu bi nhng ngi s dng khng c cp php v kh nng kim tra tnh ng n ca CSDL. Phc hi d liu, c ngha l c kh nng phc hi d liu, khng lm mt mt d liu vi cc li h thng.

viii.

1.3. c im ca mt h qun tr CSDL 1.3.1. S tru tng ho d liu: cho h thng c th s dng c, h qun tr CSDL phi tra cu hay tm kim d liu mt cch c hiu qu. iu ny dn n vic thit k cc cu trc d liu phc tp biu din d liu trong CSDL ny. Ngi pht trin che du tnh phc tp ny thng qua mt s mc tru tng n gin ho cc tng tc ca ngi s dng i vi h thng.
Khung nhn 1 Mc khung nhn Khung nhn n

Mc logic

Mc vt l

Hnh 1.1. Ba mc tru tng d liu Mc vt l: Mc thp nht ca s tru tng m t d liu c lu tr mt cch thc s nh th no. Ti mc vt l, cc cu trc d liu mc thp phc tp c m t chi tit. Mc logic: Mc cao tip theo ca s tru tng ho m t nhng d liu no c lu tr v cc mi quan h no tn ti gia cc d liu ny. Mc logic ca s tru tng c xc nh ngi qun tr CSDL, c th phi quyt nh nhng thng tin g c lu tr trong CSDL.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

Mc khung nhn: Mc cao nht ca s tru tng m t ch mt phn ca ton b CSDL. Mc d s dng cc cu trc n gin mc logic, mt s phc tp vn cn tn ti do kch thc ln ca CSDL. Thc cht nhng ngi s dng ch cn truy nhp n mt phn CSDL, do vy s tng tc ca h vi h thng ny l n gin ho v mc khung nhn ca s tru tng c xc nh. H thng c th c cung cp nhiu khung nhn i vi cng mt c s d liu.

1.3.2. Ngn ng c s d liu Mt h qun tr c s d liu thng cung cp hai kiu ngn ng khc nhau l: ngn ng m t s c s d liu v ngn ng biu din cc truy vn v cc cp nht c s d liu. Ngn ng nh ngha d liu (Data Definition Language - DDL) + Mt s CSDL c t bi mt tp cc nh ngha c biu din bi mt ngn ng c bit c gi l ngn ng nh ngha d liu. Kt qu ca vic dch cc ngn ng ny l mt tp cc bng c lu tr trong mt tp c bit c gi l t in d liu hay th mc d liu. + Mt t in d liu l mt tp cha cc siu d liu c ngha l cc d liu v d liu. Tp ny c tra cu trc khi d liu thc s c c hay c sa i trong h CSDL. + Cu trc v cc phng php truy nhp c s dng bi h CSDL c c t bi mt tp cc nh ngha trong mt kiu c bit ca DDL l ngn ng nh ngha v lu tr d liu. Ngn ng thao tc d liu (Data Manipulation Language - DML): + Cc yu cu v thao tc d liu bao gm: Tm kim thng tin c lu tr trong CSDL.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

Thm thng tin mi vo CSDL. Xo thng tin t CSDL. Thay i thng tin c lu tr trong CSDL. + Mt ngn ng thao tc d liu (DML) l mt ngn ng cho php ngi s dng truy nhp hay thao tc d liu c t chc bi m hnh d liu thch hp. C hai kiu ngn ng thao tc d liu c bn: Cc DML th tc i hi ngi s dng phi c t d liu no cn tm kim v tm kim nhng d liu ny nh th no. Cc DML phi th tc i hi ngi s dng c t d liu no cn tm kim m khng phi c t tm kim nhng d liu ny nh th no. 1.3.3. X l cu hi Cng vic ca b x l cu hi l bin i mt truy vn hay mt thao tc CSDL c th c biu din cc mc cao thnh mt dy cc yu cu i vi cc d liu lu tr trong CSDL. Thng phn kh nht ca nhim v x l cu hi l ti u ho cu hi, c ngha l la chn mt k hoch tt nht i vi h thng lu tr tr li truy vn ny nhanh nht. 1.3.4. Qun tr giao dch Thng thng mt s thao tc trn CSDL hnh thnh mt n v logic cng vic. iu ny c ngha l hoc tt c cc thao tc c thc hin hoc khng thao tc no c thc hin. Hn na s thc hin cc thao tc ny phi m bo tnh nht qun ca CSDL. Mt giao dch l mt tp hp cc thao tc m x l nh mt n v khng chia ct c. Cc h qun tr CSDL in hnh cho php ngi s dng mt hay nhiu nhm thao tc tra cu hay thay i CSDL thnh mt giao dch.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

1.3.5. Qun l lu tr Cc CSDL thng i hi mt khi lng ln khng gian lu tr. Do b nh chnh ca my tnh khng th lu tr nhiu thng tin nh vy, cc thng tin ny c lu tr cc thit b nh ngoi nh a cng, a mm,.v.v Khi x l, d liu cn phi c di chuyn t a t vo b nh chnh; s di chuyn ny l kh chm so vi tc x l ca b nh trung tm, do vy cc h CSDL phi t d liu vt l sao cho tt, ti thiu ho s yu cu chuyn d liu gia a t vo b nh chnh. 1.4. Kin trc ca mt h qun tr CSDL Chng ta s phc tho kin trc v thy cch thc ca mt h qun tr CSDL in hnh. Ta c s kin trc hnh 1.2:

Hnh 1.2. Cc thnh phn chnh ca h qun tr CSDL - D liu, siu d liu: y kit trc l thit b nh ngoi lu tr d liu v siu d liu. Trong phn ny khng ch cha d liu c tr trong CSDL m cha c cc siu d liu, tc l thng tin cu trc ca CSDL. V d: Trong

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

h qun tr c s d liu quan h, cc siu d liu bao gm cc tn ca cc quan h, tn cc thuc tnh ca cc quan h, v cc kiu d liu i vi cc thuc tnh ny. - B qun l lu tr: Nhim v ca b qun l lu tr l ly ra cc thng tin c yu cu t nhng thit b lu tr d liu v thay i nhng thng tin ny khi c yu cu bi cc mc trn n ca h thng. - B x l cu hi: B x l cu hi iu khin khng ch cc cu hi m c cc yu cu thay i d liu hay siu d liu. Nhim v ca n l tm ra cch tt nht mt thao tc c yu cu v pht ra lnh i vi b qun l lu tr v thc thi thao tc . - B qun tr giao dch: B qun tr giao dch c trch nhim m bo tnh ton vn ca h thng. N phi m bo rng mt s thao tc thc hin ng thi khng cn tr mi thao tc khc v h thng khng mt d liu thm ch c khi li h thng xy ra. + N tng tc vi b x l cu hi, do vy n phi bit d liu no c thao tc bi cc thao tc hin thi trnh s ng gia cc thao tc v cn thit n c th lm tr mt s truy vn nht nh hay mt s thao tc cp nht ng khng th xy ra. + N tng tc vi b qun l lu tr bi v cc s i vi vic bo v d liu thng ko theo vic lu tr mt nht k cc thay i i vi d liu. Hn na, vic sp th t cc thao tc mt cch thc s c nht k ny s cha trong mt bn ghi i vi mi thay i khi gp li h thng, cc thay i cha c ghi vo a c th c thc hin li. - Cc kiu thao tc i vi h qun tr CSDL: Ti nh kin trc, ta thy c 3 kiu thao tc: + Cc truy vn: y l cc thao tc hi p v d liu c lu tr trong CSDL. Chng c sinh ra theo hai cch sau: Thng qua giao din truy vn chung. V d: H qun tr CSDL quan h cho php ngi s dng nhp cc cu

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

lnh truy vn SQL m n c chuyn qua b x l cu hi v c tr li. Thng qua cc giao din chng trnh ng dng: Mt h qun tr CSDL in hnh cho php ngi lp trnh vit cc chng trnh ng dng gi n h qun tr CSDL ny v truy vn CSDL. + Cc cp nht d liu: y l cc thao tc thay i d liu nh xo, sa d liu trong CSDL. Ging nh cc truy vn, chng c th c pht ra thng qua giao din chung hoc thng qua giao din ca chng trnh. + Cc thay i s : Cc lnh ny thng c pht bi mt ngi s dng c cp php, thng l nhng ngi qun tr CSDL mi c php thay i s ca CSDL hay to lp mt CSDL mi. 1.5. Cc chc nng ca h qun tr CSDL quan h 1.5.1. Cc khi nim trong m hnh d liu quan h - Min (domain): l mt tp cc gi tr hoc cc i tng. - Thc th: Thc th l mt i tng c th hay tru tng trong th gii thc m n tn ti v c th phn bit c vi cc i tng khc. V d: Bn Nguyn Vn A l mt thc th c th. Hay Sinh vin cng l mt thc th, thc th tru tng. - Thuc tnh (Attribute): L tnh cht ca thc th. + Cc thc th c cc c tnh, c gi l cc thuc tnh. N kt hp vi mt thc th trong tp thc th t min gi tr ca thuc tnh. Thng thng, min gi tr ca mt thuc tnh l mt tp cc s nguyn, cc s thc, hay cc xu k t. + Mt thuc tnh hay mt tp thuc tnh m gi tr ca n xc nh duy nht mi thc th trong tp cc thc th c gi l kho i vi tp thc th ny.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

10

+ Mi mt thuc tnh nhn tp s cc gi tr nht nh c gi l domain ca thuc tnh . - Mt quan h (Relation): nh ngha mt cch n gin, mt quan h l mt bng d liu c cc ct l cc thuc tnh v cc hng l cc b d liu c th ca quan h. - Cc lin kt: Mt lin kt l mt s kt hp gia mt s thc th (hay quan h). V d: Mi lin kt gia phng ban v nhn vin th hin: Mt nhn vin A s thuc mt phng ban B no . + Cc lin kt mt mt: y l dng lin kt n gin, lin kt trn hai thc th l mt mt, c ngha l mi thc th trong tp thc th ny c nhiu nht mt thc th trong tp thc th kia kt hp vi n v ngc li. + Cc lin kt mt nhiu: Trong mt lin kt mt nhiu, mt thc th trong tp thc th A c kt hp vi khng hay nhiu thc th trong tp thc th B. Nhng mi thc th trong tp thc th B c kt hp vi nhiu nht mt thc th trong tp thc th A. + Cc lin kt nhiu nhiu: y l dng lin kt m mi thc th trong tp thc th ny c th lin kt vi khng hay nhiu thc th trong tp thc th kia v ngc li. V d 1.1. Cc mi lin kt gia cc thc th: LOP(MaLop, TenLop, Khoa), SINHVIEN(MaSV, Hoten, NgSinh, MaLop), MONHOC(MaMon, TenM, SDVHT) v KETQUA (MaSV, MaMon, Diem) Ta c mi quan h gia cc thc th l:
LOP MaLop TenLop Khoa SINHVIEN MaSV Hoten NgSinh MaLop KETQUA MaSV MaMon Diem MONHOC MaMon TenM SDVHT

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

11

- M hnh d liu quan h: Lm vic trn bng hay trn quan h trong : Mi ct l mt thuc tnh, mi dng l mt b (mt bn ghi). + Cc u im ca m hnh d liu quan h o Cu trc d liu d dng, khng cn hiu bit su v k thut ci t. o Ci thin tnh c lp d liu v chng trnh. o Cung cp ngn ng thao tc phi th tc. o Ti u ho cch truy xut d liu. o Tng tnh bo mt v ton vn d liu. o Cung cp cc phng php thit k c h thng. V m ra cho nhiu loi ng dng (ln v nh). + Kho ca quan h: o Kho ca quan h (key): L tp cc thuc tnh dng phn bit hai b bt k trong quan h. o Kho ngoi ca quan h (Foreign Key): Mt thuc tnh c gi l kho ngoi ca quan h nu n l thuc tnh khng kho ca quan h ny nhng l thuc tnh kho ca quan h khc. 1.5.2. Cc chc nng ca h qun tr CSDL quan h Cc chc nng ca h qun tr CSDL quan h c th c phn thnh cc tng chc nng nh hnh 1.3: - Tng giao din (Interface layer): Qun l giao din vi cc ng dng. Cc chng trnh ng dng CSDL c thc hin trn cc khung nhn (view) ca CSDL. i vi mt ng dng, khung nhn rt c ch cho vic biu din mt hnh nh c th v CSDL (c dng chung bi nhiu ng dng). Khung nhn quan h l mt quan h o, c dn xut t cc quan h c s (base relation) bng cch p dng cc php ton i s quan h.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

12

Qun l khung nhn bao gm vic phin dch cu vn tin ngi dng trn d liu ngoi thnh d liu khi nim. Nu cu vn tin ca ngi dng c din t bng cc php ton quan h, cu vn tin c p dng cho d liu khi nim vn gi nguyn dng ny. - Tng iu khin (Control Layer): chu trch nhim iu khin cu vn tin bng cch a thm cc v t ton vn ng ngha v cc v t cp quyn. - Tng x l vn tin (Query processing layer): chu trch nhim nh x cu vn tin thnh chui thao tc c ti u mc thp hn. Tng ny lin quan n vn hiu nng. N phn r cu vn tin thnh mt cy biu th cc php ton i s quan h v th tm ra mt th t ti u cho cc php ton ny. Kt xut ca tng ny l cu vn tin c din t bng i s quan h hoc mt dng m mc thp. - Tng thc thi (Execution layer): C trch nhim hng dn vic thc hin cc hoch nh truy xut, bao gm vic qun l giao dch (u thc, ti khi ng) v ng b ho cc php i s quan h. N thng dch cc php ton i s quan h bng cch gi tng truy xut d liu qua cc yu cu truy xut v cp nht. - Tng truy xut d liu (data access layer): Qun l cc cu trc d liu dng ci t cc quan h (tp tin, ch mc). N qun l cc vng m bng cch lu tm cc d liu thng c truy xut n nhiu nht. S dng tng ny lm gim thiu vic truy xut n a. - Tng duy tr nht qun (Consistency layer): chu trch nhim iu khin cc hot ng ng thi v vic ghi vo nht k cc yu cu ct nht. Tng ny cng cho php khi phc li giao dch, h thng v thit b sau khi b s c.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

13

Hnh 1.3. Cc chc nng ca h qun tr CSDL quan h

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

14

Chng 2: CC CU LNH SQL C BN Ngn ng SQL (Structured Query Language) l ngn ng truy vn c cu trc, dng thao tc vi d liu trong c s d liu cng nh to v thay i cu trc ca cc c s d liu. Trong chng ny ta s trnh by mt s cu lnh SQL c bn. 2.1. CC CU LNH NH NGHA D LIU 2.1.1. Lnh CREATE - ngha: Lnh CREATE dng to cc i tng c s d liu nh cc bng, cc view, cc tp ch s .v.v - C php: + CREATE TABLE <Tn bng>(<Danh sch: Tn_ct Kiu_ct> <iu_kin_kim_sot_dl >) + CREATE VIEW <Tn View>(<Danh sch: Tn_ct Kiu_ct> <iu_kin_kim_sot_dl >) AS Q; vi Q l mt khi cu lnh SELECT nh ngha khung nhn (view). + CREATE [UNIQUE] INDEX <tn ch s> ON <Ten bng>(Tn ct [ASC|DESC]) - Mt s kiu d liu: Integer - s nguyn; float- du phy ng; char k t, datetime- ngy thng, boolean, V d 2.1. S dng cu lnh CREATE. + CREATE TABLE S (S# Integer NOT NULL, SNAME Char(30), STATUS Integer, CITY Char(50)) PRIMARY KEY (S#); + CREATE VIEW vieS (S# Integer NOT NULL, SNAME Char(30)) AS SELECT S#, SNAME FROM S; + CREATE TABLE PHONGBAN (MaPB Char(5) NOT NULL, TenPB Char(30)) PRIMARY KEY (MaPB);

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

15

+ CREATE TABLE NHANVIEN (MaNV Char(5) NOT NULL, TenNV Char(30), Ngaysinh date, MaPB Char(5)) PRIMARY KEY (MaNV) FOREIGN KEY (MaPB) REFERENCES TO PHONGBAN; + CREATE INDEX index1 ON SP(S# ASC, P# DESC) 2.1.2. Lnh thay th sa i ALTER - ngha: Dng thay i cu trc lc ca cc i tng CSDL. - C php: + ALTER TABLE <Tn bng> <Thc hin cc lnh trn ct> Cc lnh trn ct c th l: Xa mt ct: Delete <tn ct> Thm mt ct: Add <Tn ct> Thay i tn ct: Change column <Tn ct>To<Tn ct> Xa kha chnh: Drop PRIMARY KEY Xa kha ngoi: Drop FOREIGN KEY Thit lp kha chnh: PRIMARY KEY (Tn ct) Thit lp kha ngoi: FOREIGN KEY (Tn ct) REFERENCES TO <tn bng ngoi> + ALTER VIEW <Tn View>(<Danh sch: Tn_ct Kiu_ct> <iu_kin_kim_sot_dl >) AS Q; vi Q l mt khi cu lnh SELECT nh ngha khung nhn (view). V d 2.2. Thay i cu trc ca bng NHANVIEN ALTER TABLE NHANVIEN Add Quequan char(50); ALTER TABLE NHANVIEN Delete Ngaysinh; V d 2.3. Thay i khung nhn vieS CREATE VIEW vieS AS SELECT S#, SNAME, CITY FROM S

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

16

2.1.3. Xo cu trc DROP - ngha: Dng xa cc i tng c s d liu nh Table, View, Index, .v.v - C php: DROP TABLE <Tn bng> DROP VIEW <Tn view> DROP INDEX <Tn index> 2.2. CC CU LNH CP NHT D LIU 2.2.1. Lnh Insert - ngha: Dng chn mt hng hoc mt s hng cho bng. - C php: + INSERT INTO <Tn bng> (Danh sch cc ct) VALUES (Danh sch cc gi tr) hoc + INSERT INTO <Tn bng> (Danh sch cc ct) (Cc cu hi con); V d 2.4. Chn d liu vo bng S. INSERT INTO S (S#, SNAME, STATUS) VALUES (s1, Smith, 20, Paris); INSERT INTO S SELECT * FROM W WHERE CITY="Paris"; 2.2.2. Lnh Update - ngha: Dng sa i d liu. - C php: UPDATE <Tn bng> SET <Tn_ct_1=Biu_thc_1, Tn_ct_2=Biu_thc_2, >
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

17

[WHERE <iu kin>] V d 2.5. S dng lnh Update UPDATE SINHVIEN SET TenSV="Nguyn Th Hnh" Where MaSV="20042390" UPDATE HangHoa SET Dongia=Dongia*1.1 Where TenHH IS LIKE 'Bia %' and Dongia<3500 2.2.2. Lnh Delete - ngha: Xo mt s hng trong bng. - C php: DELETE FROM <Tn bng> WHERE <iu kin> V d 2.6. Xo tt c cc hng trong bng KETQUA c trng Diem<5 DELETE FROM KETQUA WHERE Diem<5; 2.3. KIM SOT D LIU 2.3.1. Trao quyn GRANT - ngha: Dng trao quyn cho mt acount no . - C php: GRANT <Quyn> ON <Tn bng/ Tn View> TO <user> [WITH GRANT OPITION] Cc quyn c th trao l: All, Select, update, delete, insert, index, alter, read, write, User c th l: Public, tn mt user c th, - Ch : Nu c trao quyn vi ch nh WITH GRANT OPITION th anh ta c th trao li quyn y cho ngi khc. V d 2.7. Trao quyn Select cho acount Lannt GRANT Select ON SINHVIEN TO Lannt WITH GRANT OPITION 2.3.2. Thu hi quyn REVOTE

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

18

- ngha: Dng thu hi quyn ca mt acount no . - C php: REVOTE <Quyn> ON <Tn bng/ Tn View> FROM <user> V d 2.8. Thu hi quyn Select ca acount Lannt REVOTE Select ON SINHVIEN FROM Lannt; 2.4. TRUY VN D LIU Khi cu lnh ph dng: SELECT - FROM WHERE. Ta c th s dng theo c php chung nh sau: SELECT [*| DISTINCT] <Danh sch cc ct [AS <B danh>]> FROM <Danh sch Tn bng/Tn View> [WHERE <Biu thc iu kin>] [GROUP BY <Danh sch ct>] [HAVING <iu kin>] [ORDER BY <Tn ct/ S th t ct/Biu thc> [ASC/DESC]] 2.4.1. Tm kim theo cu hi n gin - Tm kim n gin: + Nu xut hin gi tr * ngha l xem ton b cc ct ca bng. Select * From SINHVIEN; + Nu s dng DISTINCT th s ly gi tr i din. Select Distinct S#, P# From SP; - X l xu: dng ton t [NOT] LIKE <Mu so snh> + Dng du gch di thay cho mt k t. + Dng du % thay cho mt dy cc k t tu . V d 2.9. Cho bng h s sinh vin HOSOSV(MaSV, Hodem, TenSV, Ngaysinh, MaLop). Hy cho bit m v h tn sinh vin c hai ch u l 'Ba' Select MaSV, Hodem+TenSV as Hoten From HOSOSV
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

19

Where TenSV like 'Ba%' V d 2.10. Cho bng h s sinh vin HOSOSV(MaSV, Hodem, TenSV, Ngaysinh, MaLop). Hy cho bit m v h tn sinh vin c khng c hai ch u l 'Ba' Select MaSV, Hodem+TenSV as Hoten From HOSOSV Where TenSV like 'Ba%' - S dng Between v IN xc nh phm vi: V d 2.11. Cho bng thng tin sch mn SACHMUON(MaBD, MaSach, NgayMuon, NgayTra). Hy cho bit m cc bn c mn sch ca th vin trong khong ngy {1/1/2008} v {31/3/2008} Select MaBanoc From SACHMUON Where NgayMuon Between {1/1/2000} and {31/3/2000} 2.4.2. S dng cc hm th vin Cc hm th vin thc hin cc thao tc nh thng k d liu, tnh ton d liu c sn nh: Count(): Dng m cc bng ghi, Max(): Tr v gi tr ln nht ca mt tp hp cc gi tr, Min(): Tr v gi tr ln nht ca mt tp hp cc gi tr, Sum(): Tr v tng gi tr ca mt tp hp cc gi tr, Avg():Tr v gi tr trung bnh ca mt tp hp cc gi tr,

V d 2.12.: Cho bng DIEM(MaSV, MaMH, DiemL1, DiemL2). Hy xem sinh vin c m SV061001 tham gia thi bao nhiu mn: Select Count(MaMH) AS Tongso From DIEM where MaSV='SV061001'; V d 2.13: Cho bit im thi cao nht ln 1 ca mn c m '03AB'

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

20

Select Max(DiemL1) as DiemCN From DIEM Where MaMH='03AB'; V d 2.14. Cho bit chnh lnh gia im thi cao nht v thp nht ca mn c m mn hc l '03AB' Select (Max(DiemL1) - Min (DiemL1)) As Chenh_Lenh From DIEM where MaMT='03AB'; 2.4.3. Tm kim nh cc mnh - S dng phn nhm GROUP BY: Mnh GROUP BY c s dng to hiu qu sp xp v tnh ton theo tng phn nhm. V d 2.15. Cho bit tnh hnh thi ca tng sinh vin: Select MaSV, MaMH, DiemL1, DiemL2 From DIEM Group By MaSV - S dng HAVING: Mnh HAVING dng t iu kin lc cho cc phn nhm con. V d 2.16. Cho bng mt hng c cung cp SP(S#, P#, QTY). Tm m nhng nh cung cp cung cp t nht 2 mt hng: Select S# From SP Group By S# Having Count(Distinct P#)>=2; V d 2 .17. Tm m cc sinh vin khng c mn thi no di 5 Select MaSV From DIEM Group By MaSV Having Min(Diem)>=5; Ch : Having i sau Group By t iu kin chn lc ra nhng phn nhm tho mn iu kin sau Having. Nu khng c t kho Group By th Having s tc ng trn ton bng coi nh mt phn nhm duy nht.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

21

- S dng Order By: c s dng to hiu qu sp xp d liu. Ta c th sp xp theo chiu tng (ASC) hoc gim (DESC). + Ta c th tc ng sp xp li trn tng phn nhm bi Order By. V d 2.18. Cho bit tnh hnh thi ln 1 ca mi sinh vin sao cho kt qu im thi c sp xp gim dn. SELECT MaSV, MaMT, iemL1 GROUP BY MaSV ORDER BY Diem DESC - Ch : Tng t HAVING, nu trc Order by khng c Group By th hiu qu sp xp d liu s tc ng trn ton bng v bng c coi nh mt phn nhm chnh. 2.4.4. Cu hi phc tp Khi thc hin cc truy vn lm vic vi d liu t 2 bng tr nn th iu kin x l phc tp hn. - T kt ni: V d 2.19. Kim tra bng kt qu thi KETQUA(SoBD, MaMT, Diem) c b nhp trng hay khng? Ngha l nhp trng MaSV, MaMT nhng im thi li khc nhau (nhp 2 ln). SELECT a.SoBD, a.MaMT, a.Diem, b.Diem From KETQUA a, KETQUA b Where (a.SoBD=b.SoBD) and (a.MaMT=b.MaMT) and (a.Diem>b.Diem) - Kt ni nhiu bng: V d 2.20. Cho bit kt qu thi mn Ton ca cc sinh vin. + CREATE VIEW MaToan AS SELECT MaMT From MONTHI Where TenMon='Ton' + CREATE VIEW TAM AS SELECT a.SoBD, a.Diem From KETQUA a, MaToan b
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

22

Where a.MaMT=b.MaMT; + SELECT a.SoBD, TenSV, a.Diem From Tam a, THISINH b Where a.SoBD=b.SoBD V d 2.21. Lin kt nhiu bng authors, titleauthor v title. SELECT au_lname, au_fname, title, price FROM authors JOIN titleauthor ON authors.au_id = titleauthor.au_id JOIN titles ON titleauthor.title_id = titles.title_id ORDER BY au_lname, au_fname - nh x lng V d 2.22. Cho cc quan h: S(S#, SNAME, STATUS, CITY) SP(S#, P#, QTY) P(P#, PNAME, COLOR, WEIGH) Hy cho bit m v tn cc hng c bn sn phm mu . SELECT S#, SNAME From S Where S# IN (SELECT S# From SP Where P# IN (Select P# From P Where COLOR='Red')); - S dng cc lng t: EXISTS, ANY, ALL, V d 2.23. Cho cc bng trong v d 2.22. Tm cc nh cung cp cung cp t nht mt mt hng no . SELECT * From S Where EXISTS (SELECT * From SP Where SP.S# =S.S#); Ta c th thay th bng cu lnh: SELECT * From S Where 0 < (SELECT Count(*) From SP Where SP.S#=S.S#); V d 2.24. Tm tn nhng mt hng c m s mt hng m mt hng no m hng S1 bn. SELECT PNAME From P Where S# = ANY

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

23

(SELECT P# From SP Where S#='S1'); V d 2.25. Tm nhng hng cung cp s lng mt ln mt mt hng no > s lng mi ln ca cc hng cung cp. SELECT S From SP Where QTY>= ALL (SELECT QTY From SP ); hay SELECT S From SP Where QTY= (SELECT Max(QTY) From SP );

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

24

Chng 3: H QUN TR C S D LIU SQL SERVER 3.1. TNG QUAN V H QUN TR SQL SERVER 3.1.1. Gii thiu h qun tr SQL Server Microsoft SQL Server l mt h qun tr c s d liu quan h (Relation Database Management System - RDBMS), cung cp cch t chc d liu bng cch lu chng vo cc bng. D liu quan h c lu tr trong cc bng v cc quan h c nh ngha gia cc bng vi nhau. Ngi dng truy cp d liu trn Server thng qua ng dng. Ngi qun tr CSDL truy cp Server trc tip thc hin cc chc nng cu hnh, qun tr v thc hin cc thao tc bo tr CSDL. Ngoi ra, SQL Server l mt CSDL c kh nng m rng, ngha l chng c th lu mt lng ln d liu v h tr tnh nng cho php nhiu ngi dng truy cp d liu ng thi. Cc phin bn ca SQL Server ph bin hin ny trn th trng l SQL Server 7.0, SQL Server 2000, SQL Server 2005, SQL Server 2008. Trong gio trnh ny, tc gi gii thiu vi cc bn trn hai phin bn SQL Server 2000, SQL Server 2005. 3.1.2.Cc thnh phn ca SQL Server 3.1.2.1. Cc thnh phn ca SQL Server 2000 SQL Server cung cp mt s loi thnh phn khc nhau: Nhn ca n l cc thnh phn server, cc thnh phn ny c thc hin nh windows 32 bit. Cc cng c ha da trn client v cc dng tin ch phc v cho cng tc qun tr. Cc cng c v tin ch ny s dng s dng cc thnh phn giao tip client do SQL Server 2000 cung cp. Cc thnh phn giao tip cung cp cc cch khc nhau m

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

25

trong ng dng client c th truy cp d liu thng qua cc thnh phn server. a) Cc thnh phn server Cc thnh phn server ca SQL Server 2000 thng c thc hin nh cc dch v Windows 32 bit. Do cc dch v ca SQL Server v SQL Server Agent c th chy nh cc ng dng c lp trn bt k nn tng no c h tr h iu hnh Windows. Cc thnh phn Server c m t trong bng 3.1: Bng 3.1. Cc thnh phn server ca SQL Server 2000 Thnh phn server Chc nng Dch v MSSQLServer thc thi c my CSDL SQL Server 2000. C mt dch v ny cho mi th hin ca SQL Server 2000.

Dch v SQL Server

Dch v v cc dch MSSQLServerOLAPService thc thi cc dch v v phn tch ca phn tch ca SQL Server 2000. Ch c mt dch v SQL Server 2000 khng lin quan n s th hin ca SQL Server 2000. Dch v SQL Server Dch v SQLServerAgent thc thi cc tc nhn chy Agent cc tc v qun tr c nh thi gian biu ca SQL Server 2000. Dch v tm kim Dch v tm kim Microsoft thc thi c my tm kim ton vn bn. Ch c mt dch v, khng lin quan n s th hin ca SQL Server 2000.

Dch v MS DTC - Thnh phn iu phi giao dch phn tn, qun l Distributed cc giao dch phn tn gia cc th hin ca SQL Transaction Server 2000. Ch c mt dch v, khng lin quan Coordinator n s th hin ca SQL Server 2000.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

26

SQL Server 2000 cung cp cc giao din ha gip cho ngi s dng s dng cc dch v ca SQL Server 2000 (Hnh 3.1. v Bng 3.2).

Hnh 3.1. Cc giao din ha ca SQL Server 2000. Bng 3.2 Cc cng c giao din ha ca SQL Server 2000. Cng c SQL Server Enterprise Manager SQL Query Analyzer Chc nng y l cng c qun tr CSDL server chnh, n cung cp mt giao tip vi ngi dng Microsoft Management Console (MMC). Dng to v qun l cc i tng CSDL v kim tra cc pht biu Transact-SQL, cc b lnh v cc script mt cch tng tc. Gim st v ghi nhn cc s kin SQL Server 2000 chn phn tch v xem li.

SQL Profiler

SQL Server Service ng dng nm trn thanh task bar ca Windows Manager c dng chy, tm dng hoc thay i cc dch v SQL Server 2000. Client Network c dng qun l Net-Libraries ca client v
B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

Bi ging H qun tr CSDL

27

Utility Server Utility

nh ngha cc b danh server. Network Dng qun l Net-Libraries ca server bao gm thit lp m ha SSL.

b) Cc thnh phn giao tip Client. Ngi dng truy cp SQL Server 2000 thng qua cc ng dng client, SQL Server 2000 cung cp hai kiu ng dng client chnh: Cc ng dng CSDL quan h, l kiu ng dng truyn thng dng mi trng client/server 2 lp. Cc ng dng ny gi cc pht biu T-SQL n c my CSDL quan h v nhn kt qu tr v nh tp kt qu quan h. Cc ng dng Internet, chng l thnh phn ca nn tng Microsoft.NET. Chng gi cc pht biu T-SQL hoc cc truy vn Xpath ti c my CSDL quan h v nhn v kt qu dng XML.

Cc tin ch dng lnh thng c s dng do SQL Server 2000 cung cp cho trong bng 3.3. Bng 3.3 Cc tin ch dng lnh ca SQL Server 2000. Tin ch Osql Chc nng Tin ch ny cho php truy vn tng tc mt th hin ca SQL Server 2000 bng cc pht biu T-SQL, cc th tc v cc script. Dng chy, dng, tm dng, ci t, xa hoc thay i cc dch v SQL Server 2000. Tin ch ny thu thp v lu tr cc thng tin chun on x l v n gin ha thng tin thu thp bi dch v h tr sn phm Microsoft. Tin ch ny sao chp d liu gia mt th hin ca SQL Server 2000 v tp tin d liu theo nh dng ca ngi dng.

Scm (Server Control Manager) Sqldiag

Bcp

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

28

Dtsrun Sqlmaint

Tin ch ny thc thi cc gi c to bi DTS. Tin ch ny thc thi cc hot ng bo tr trn mt hoc nhiu CSDL. Nhng hot ng bao gm vic kim tra tnh nht qun d liu, sao lu tp tin d liu v tp tin giao dch, cp nht cc thng k phn tn, xy dng li cc ch mc.

3.1.2.2. Cc thnh phn ca SQL Server 2005 SQL Server 2005 nng cao hiu nng, tin cy, kh nng lp trnh n gin v giao din d s dng hn so vi SQL Server 2000. SQL Server 2005 tp trung vo kh nng x l giao dch trc tuyn (online transaction processing - OLTP), ng dng thng mi in t (e- ecommerce) v kho d liu (data warehousing). Ngoi ra nhng ci tin quan trng trong SQL Server 2005 l thm cc dch v mi nh: dch v bo co (reporting service), service broker v s thay i ng k trong c my c s d liu. a) Cc phin bn ca SQL Server 2005: Trc khi i vo cc thnh phn ca SQL Server 2005, ta xt cc phin bn ca SQL Server 2005. SQL Server 2005 c s dng rng ri cho nhiu i tng khc nhau nn Microsoft cung cp nhiu phin bn khc nhau cho ph hp vi cc yu cu v chi ph, thi gian thc hin, ca cc t chc, c nhn. Nm phin bn ca SQL Server 2005 l: + Microsoft SQL Server 2005 Enterprise Edition + Microsoft SQL Server 2005 Standard Edition + Microsoft SQL Server 2005 Workgroup Edition + Microsoft SQL Server 2005 Developer Edition + Microsoft SQL Server 2005 Express Edition Hu ht cc t chc u chn trong ba phin bn SQL Server 2005 Enterprise Edition, SQL Server 2005 Standard Edition, v SQL Server 2005 Workgroup Edition. Cc t chc chn mt trong ba phin bn ny vi l do l

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

29

ch c cc phin bn Enterprise, Standard, v Workgroup c ci t v s dng trong mi trng server phc v cho hot ng thc t. + SQL Server 2005 Enterprise Edition (32-bit v 64-bit) Enterprise Edition c s dng trong cc doanh nghip, t chc c cc mc yu cu x l giao dch trc tuyn trn din rng (online transaction processing - OLTP), kh nng phn tch d liu phc tp cao, h thng kho d liu (data warehousing systems) v web sites. Enterprise Edition ph hp cho cc t chc ln v cc yu cu phc tp. + SQL Server 2005 Standard Edition (32-bit v 64-bit) Standard Edition l phin bn phc v cho vic qun tr v phn tch d liu ph hp cho cc doanh nghip, t chc va v nh. N bao gm cc gii php cn thit cho thng mi in t (ecommerce), kho d liu (data warehousing) v dng doanh nghip (line-of-business). + SQL Server 2005 Workgroup Edition (32-bit only) Workgroup Edition l gii php qun tr d liu ph hp cho cc doanh nghip, t chc nh ch cn mt c s d liu khng gii hn kch thc hoc s ngi s dng. Workgroup Edition l l tng cho cc mc c s d liu tin cy, mnh m v d qun tr. + SQL Server 2005 Developer Edition (32-bit v 64-bit) Developer Edition c tt c cc tnh nng ca phin bn SQL Server 2005 Enterprise Edition, nhng n ch l phin bn s dng cho pht trin v kim tra ng dng. Phin bn ny ph hp cho cc c nhn, t chc xy dng v kim tra ng dng. + SQL Server 2005 Express Edition (32-bit only) SQL Server Express, d s dng v qun tr c s d liu n gin. c tch hp vi Microsoft Visual Studio 2005, SQL Server Express tr nn d dng pht trin cc ng dng d liu giu kh nng, an ton trong lu tr, v nhanh chng trin khai.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

30

SQL Server Express l phin bn min ph, c th dng nh mt c s d liu my khch hoc c s d liu my ch n gin. SQL Server Express l la chn tt cho nhng ngi dng ch cn mt phin bn SQL Server 2005 nh gn, dng trn my ch c cu hnh thp, nhng nh pht trin ng dng khng chuyn hay nhng ngi yu thch xy dng cc ng dng nh. b) Cc thnh phn Server ca SQL Server 2005: Cc thnh phn server ca SQL Server 2005 c cho trong bng 3.4. Bng 3.4 Cc thnh phn server ca SQL Server 2005. Thnh phn Server Chc nng C my c s d liu bao gm Database Engine, li dch v cho vic lu tr, x l v bo mt d liu, sao lu v ng b (Replication), tm kim ton vn (Full-Text Search), v cc cng c cho vic qun tr d liu quan h v XML. Analysis Services bao gm cc cng c cho vic to v qun l tin trnh phn tch tr tuyn (online analytical processing - OLAP) v cc ng dng khai thc d liu. Reporting Services bao gm cc thnh phn server v client cho vic to, qun l v trin khai cc bo co. Reporting Services cng l nn tng cho vic pht trin v xy dng cc ng dng bo co. Dch v thng bo Notification Services l nn tng cho s pht trin v trin khai cc ng dng to v gi thng bo. Notification Services c th gi thng bo theo ch thi n hng ngn ngi ng k s dng nhiu loi thit b khc nhau.

SQL Server Database

Analysis Services

Reporting Services

Notification Services

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

31

Integration Services

Integration Services l mt tp hp cc cng c ha v cc i tng lp trnh cho vic di chuyn, sao chp v chuyn i d liu.

c) Cc thnh phn Client Bng 3.5 Cc thnh phn client ca SQL Server 2005. Thnh phn Client Connectivity Components Chc nng L cc thnh phn cho vic truyn thng gia clients v servers, v cc th vin mng nh DBLibrary, ODBC, and OLE DB.

c) Cc cng c ha Cc cng c giao din ha gip cho vic truy xut v qun tr SQL Server c thay i kh nhiu so vi cc phin bn trc , cc cng c qun tr c cho trong bng 3.6. v hnh 3.2.

Hnh 3.2. Cc giao din ha ca SQL Server 2005. Bng 3.5 Cc cng c qun tr trn SQL Server 2005.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

32

Management tools

Chc nng SQL Server Management Studio (SSMS), l cng c mi trn Microsoft SQL Server 2005, n l mt mi trng c tch hp cho vic truy xut, cu hnh, qun tr v pht trin tt c cc thnh phn ca SQL Server. SSMS kt hp cc tnh nng ca Enterprise Manager, Query Analyzer, v Analysis Manager, c bao hm trong cc phin bn trc ca SQL Server, thnh mt mi trng n m cung cp truy xut SQL Server pht trin v qun tr tt c cc mc k nng trn. SQL Server Configuration Manager cung cp cc qun tr cu hnh c s cho cc dch v SQL Server (SQL Server services), cc giao thc server (server protocols), cc giao thc client (client protocols) v cc b danh client (client aliases). SQL Server Profiler cung cp giao din ngi dng ha cho vic gim st th hin ca Database Engine hoc th hin ca Analysis Services. Database Engine Tuning Advisor c vn, gip to cc tp ti u cc ch s (indexes), indexed views, v cc phn vng (partitions).

SQL Server Management Studio

SQL Server Configuration Manager

SQL Server Profiler

Database Engine Tuning Advisor

3.1.3. Qun l cc dch v ca SQL Server. 3.1.3.1. Qun l cc dch v ca SQL Server 2000 a) S dng SQL Server Service Manager Dch v l mt chng trnh hay mt tin trnh thc hin mt chc nng c th h tr chng trnh khc. SQL Server 2000 cung cp cc dch v: Dch v SQL Server: Khi khi ng SQL Server th dch v SQL Server c khi ng trn Windows. Dch v ny qun l cc
B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

Bi ging H qun tr CSDL

33

tp tin CSDL, x l cc pht biu Transaction SQL, cp pht ti nguyn gia cc kt ni ngi dng ng thi, m bo tnh nht qun d liu,.v.v Dch v SQL Server Agent: Dch v ny h tr lp cc chng trnh, thc thi tc v, cnh bo, thng bo v k hoch bo tr CSDL. N cho php ta thc hin t ng ha cc tc v bo tr CSDL. Dch v Distributed Transaction Coordinator: L trnh qun l giao dch cung cp cc kh nng bao gm nhiu ngun d liu khc nhau k c cc CSDL t xa trong cc giao dch ng dng.

Khi ng hoc dng cc dch v SQL Server s dng trnh SQL Server Service Manager thc hin theo cc bc sau: 1. Vo start/Programs/Microsoft SQL Server/Service Manager; Hoc di gc phi ca mn hnh trn thanh task bar h thng ca windows, doubleclick vo biu tng Service Manager. Khi ca s SQL Server Service Manager xut hin nh hnh 3.3. Trong danh sch Server chn tn server v danh sch Service chn dch v SQL Server. Click nt Start/Continue khi chy dch v; Click nt Pause tm dng dch v, tm dng dch v ngn chn ngi dng ng nhp vo SQL Server v c thi gian cho ngi dng ang kt ni c thi gian hon tt cc tc v v thot khi SQL Server trc khi ta ng SQL Server; Click vo nt Stop dng dch v.

2. 3.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

34

Hnh 3.3. ng dng SQL Server Service Manager 4. Trong khi chy Service Manager, trng thi hin th ca cc dch v c mc nh l 5giy, thay i thay i thi gian cp nht, ta click chut vo biu tng gc trn bn tri ca SQL Server Service Manager, chn Options xut hin hp thoi SQL Server Service Manager Options nhp vo khong thi gian kim sot vng mi cho cc dch v, chng hn l 10 (Hnh 3.4).

Hnh 3.4. SQL Server Service Manager Options b) S dng Enterprise Manager Enterprise Manager l thnh phn Microsoft Management Console (MMC). MMC l ng dng trung tm dng qun l tt c cc giao tip ca h thng. N cho php thc hin cc tc v sau: + Khi ng, dng, tm dng Server. + ng k server, + Cu hnh server cc b v t xa + Cu hnh v qun l cc th hin ca server, + Thit lp bo mt ng nhp, thm ngi dng, ngi qun tr h thng. + Gn mt khu cho ngi qun tr h thng,
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

35

+ To v lp thi gian biu thc thi cng vic, + Thit lp v qun l CSDL, bng, ch mc, view, stored proceduce, trigger, + Qun l cc dch v SQL server khc, * Thay i mt khu mc nh Tt c cc SQL server u c mt ti khon qun tr mc nh sn l sa (system administrator). Lc mi ci ti khon ny cha c gn mt khu. m bo mc bo mt cao nht cho SQL server ta phi gn cho ti khon sa mt mt khu. Khi gn mt khu ta thc hin theo cc bc sau: 1. Trong Enterprise Manager chn tn server 2. Chn Security/Logins hin th tt c cc ti khon ngi dng. 3. Right click chut ln ti khon sa, v chn Properties, xut hin ca s SQL Server Login Properties nh hnh 3.5. 4. Nhp mt khu mi vo hp Password sau click OK him h hp thoi Confirm Password. 5. Trong hp thoi Confirm Password nhp li mt khu trn xc nhn li mt khu v chn OK.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

36

Hnh 3.5. Thay i mt khu ti khon sa. 3.1.3.2. Qun l cc dch v ca SQL Server 2005 a) S dng SQL Server Configuration Manager SQL Server Configuration Manager l cng c qun l cc dch v kt hp vi SQL Server, cu hnh cc giao thc mng c s dng bi SQL Server, v qun l cu hnh kt ni mng t cc my tnh trm SQL Server. SQL Server Configuration Manager kt hp cc chc nng ca cc cng c trong phin bn SQL Server 2000 l: Server Network Utility, Client Network Utility, v Service Manager. Khi ng hoc dng cc dch v SQL Server s dng SQL Server Configuration Manager ta thc hin theo cc bc sau: 1. Vo start/Programs/Microsoft SQL Server 2005/Configuration Tools/SQL Server Configuration Manager, xut hin ca s SQL Server Configuration Manager 2. Chn SQL Server 2005 Services, trong khu vc chi tit bn phi, right click ln th hin ca SQL Server m ta mun khi chy hoc dng. Gi s SQL Server (SQLEXPRESS) nh hnh 3.6. + Start: Khi chy th hin ca SQL Server + Stop: Dng hot ng ca th hin SQL Server. + Pause: Tm dng hot ng ca th hin SQL Server + Restart: Khi ng li th hin ca SQL Server

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

37

Hnh 3.6. Ca s SQL Server Configuration Manager. 3. Mun khi chy t ng dch v SQL Server, trong ca s trn chn Properties. Trong hp thoi SQL Server Properties, chn tab Service v chn thuc tnh Start Mode l Automatic.

Hnh 3.7. Ca s SQL Server Properties.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

38

b) S dng SQL Server Management Studio Microsoft SQL Server Management Studio l mi trng tch hp cho vic truy cp, cu hnh, qun l, qun tr v pht trin tt c cc thnh phn ca SQL Server. SQL Server Management Studio kt hp mt nhm rng ln cc cng c ha giu trnh bin tp (script editors) cung cp cc truy xut n SQL Server pht trin v qun tr tt c cc mc k nng. V c th dng n qun tr SQL Server 2000. SQL Server Management Studio kt hp cc tnh nng ca Enterprise Manager, Query Analyzer, v Analysis Manager trong phin bn trc. Thm vo , SQL Server Management Studio lm vic vi tt c cc thnh phn cu SQL Server nh l: Reporting Services, Integration Services, SQL Server Mobile, v Notification Services. Microsoft SQL Server Management Studio bao gm cc tnh nng tng qut sau: + Cung cp hu ht cc tc v qun tr cho SQL Server 2005 v SQL Server 2000. + L mi trng n, tch hp cho vic qun tr v trao quyn SQL Server Database Engine. + Cc hp thoi mi cho vic qun l cc i tng trong SQL Server Database Engine, Analysis Services, Reporting Services, Notification Services, v SQL Server Mobile, cho php ta thc thi cc hnh ng ngay lp tc, gi chng ti Code Editor, hoc to tp lnh cho ln thc thi tip theo. + Cc hp thoi cho php truy cp n nhiu iu khin trong khi hp thoi ang c m. + Lp lch cho php ta thc thi cc hnh ng ca cc hp thoi qun tr. + Export v import ng k server SQL Server Management Studio t mt mi trng Management Studio ny n mi trng khc.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

39

+ Save hoc in file XML Showplan hoc Deadlock files c sinh bi SQL Server Profiler, xem li, hoc gi chng ti administrators phn tch.v.v truy cp vo SQL Server Management Studio: 1. chy SQL Server Management Studio, trn thanh taskbar, click Start/ Programs/Microsoft SQL Server 2005, v sau click SQL Server Management Studio. 2. Khi khi chy SQL Server Management Studio, mt hp thoi Connect to Server (Hnh 3.8) xut hin. Ta c th chn mt th hin ca Server kt ni hoc khng chn mt th hin no c.

Hnh 3.8. Ca s Connect to Server. + Server type: Chn Database Engine kt ni n c my c s d liu. + Server name: chn hoc nhp tn server + Authentication: Chn ch xc thc l Windows Authentication hoc SQL Server Authentication, nu chn SQL Server Authentication th ta phi cung cp thng tin cho cc mc Login v Password. + Login: Nhp tn ng nhp

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

40

+ Password: Mt khu ca tn ng nhp + Remember password: Ty chn c chn l ng nhp sau khng phi nh mt khu. Sau hp thoi Connect to Server cho vo ca s SQL Server Management Studio (Hnh 3.9)

Hnh 3.9. Ca s SQL Server Management Studio. * ng k Server Ca s Registered Servers trong SQL Server Management Studio cha danh sch cc th hin danh sch cc server ng k. Ta s dng ca s Registered Servers nhm mc ch: + Lu thng tin kt ni cho cc th hin ca SQL Server trn mng. + Hin th mt th hin ang chy hay khng chy

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

41

+ Kt ni ti mt th hin trong ca s Object Explorer hoc Query Editor + Nhm cc server ng k mt th hin ca SQL Server ta thc hin cc bc sau 1. Vo View\chn Registered Servers xut hin ca s Registered Servers hnh 3.10. 2. Chn biu tng kiu th hin mun ng k, theo th t t tri sang phi l Database Engine, Analysis Services, Reporting Services, SQL Server Mobile v Integration Services. Ta chn Database Engine.

Hnh 3.10. Ca s Registered Servers. 3. Right click ln biu tng hoc vng trng chn New\Server Registration xut hin ca s New Server Registration (Hnh 3.11)

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

42

Hnh 3.11. Ca s New Server Registration. Trong ca s ny ta thc hin cc la chn sau: + Server Name: Nhp hoc chn tn th hin ca SQL Server t hp danh sch Server Name, c th chn <Browser for more > t tm cc th hin ca SQL Server trn mng. + Authentication: Chn ch xc thc, tng t nh trong ca s Connect to Server. + Registered server name: Tn ca th hin trn ca s Registered Servers. + Nt Test: Dng kim tra xem kt ni c thnh cng hay khng?

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

43

+ Nt Save: Dng lu thng tin ng k. kt ni ti th hin ca SQL Server v hin th n trong ca s Object Explorer hoc to truy vn mi ta thc hin cc bc sau: 1. Trong ca s Registered Servers chn biu tng kiu th hin mun kt ni. Ta chn Database Engine. 2. Right click ln th hin mun kt ni, chn Connect v chn: + New Query: to mt truy vn kt ni ti th hin ny. + Object Explorer: hin th n trong ca s Object Explorer. * Thay i mt khu mc nh Thay i mt khu cho ti khon ng nhp sa ta thc hin theo cc bc nh sau: 1. Trong ca s Object Explorer ca SQL Server Management Studio chn tn th hin ca server 2. Chn Security/Logins hin th tt c cc ti khon ngi dng. 3. Right click chut ln ti khon sa, v chn Properties, xut hin ca s Login Properties nh hnh 3.12.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

44

Hnh 3.12. Ca s Login Properties.

+ Trong tab General: Nhp mt khu mi vo hp Password v xc nhn mt khu vo Confirm Password. + Trong tab Status, mc Login chn Enabled cho php c th login vo theo ti khon sa, hoc Disabled khng th login vo theo ti khon sa.

3.2. LM VIC VI CC I TNG TRONG SQL SERVER

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

45

3.2.1. C s d liu - Database a) Cc Database h thng Khi ci t SQL Server c 4 Database h thng c ci t, l: master: Ghi nhn thng tin cp h thng, thng tin khi to SQL Server v thit lp cu hnh SQL Server. Database ny cng ghi nhn tt c cc ti khon ng nhp, s tn ti ca cc Database khc, v tr tp tin chnh cho tt c Database ngi dng. tempdb: Gi cc bng tm, cc stored procedure tm,.v.v... c dng cho cc nhu cu lu tr tm ca SQL Server. model: l khun mu cho tt c cc CSDL khc c to trn h thng k c tempdb. Database model phi c tn ti trn h thng, bi v n c dng to li tempdb mi khi SQL server c khi ng. msdb: Gi cc bng m SQL Server Agent dng lp thi gian biu thc thi cc cng vic, cc cnh bo v cc operator.

b) To Database to Database trong SQL Server 2000 , ta c 3 cch khc nhau to: + S dng Create Database Wizard + SQL Server Enterprise Manager + Dng T-SQL Trong SQL Server 2005 , ta c 2 cch khc nhau to: + SQL Server Management Studio + Dng T-SQL * S dng Create Database Wizard trn SQL Server 2000 : 1. Khi ng SQL Server Enterprise Manager, chn tn server cc b v vo menu Tools\Wizards Xut hin ca s Select Wizard hnh 3.13.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

46

Hnh 3.13. Ca s Select Wizard

Hnh 3.14. Ca s Welcome to Create Database Wizard

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

47

2. 3.

Chn Create Database Wizard v chn OK Xut hin ca s Ca s Welcome to Create Database Wizard hnh 3.14. Click Next Xut hin ca s 3.15. Name the Database And Specify its Location. Nhp tn Database v v tr lu cc file c s d liu v file log v chn Next.

Hnh 3.15. Ca s Name the Database And Specify its Location 4. Mn hnh Name the Database files (hnh 3.16), nhp tn tp tin d liu chnh (c th dng tn mc) v kch thc khi to cho tp tin . Sau chn Next Xut hin ca s 3.17. Theo ty chn mc nh: Tp tin CSDL t ng gia tng v gia tng 10%, khng gii hn dung lng ti a. Ta c th thay i cc tham s thng qua cc ty chn: + Do not automatically grow the data file: Khng t ng gia tng kch thc ca file d liu. + Automatically grow the data file: T ng gia tng kch thc ca file d liu.

5.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

48

+ Grow the file in megabytes (MB): Gia tng theo MB. + Grow the file by percent: Gia tng theo phn trm. + Unrestricted file growth: Gia tng khng gii hn cn trn ca file. + Restricted file growth to MB: Gii hn cn trn ca file theo MB. Chn Next. Xut hin ca s Name the Transaction Log Files hnh 3.18. 6. 7. Nhp tn tp tin bn ghi giao dch v kch thc khi to chng. Chn Next. Xut hin ca s Define the Transaction Log File Growth. Cc thng tin in tng t nh ca s Define the Database file Growth. Chn Next tip tc. Chn Finish kt thc.

8.

Hnh 3.16. Ca s Name the Database files

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

49

Hnh 3.17. Ca s Define the Database file Growth

Hnh 3.18. Ca s Name the Transaction Log Files

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

50

Hnh 3.19. Ca s Define the Transaction Log File Growth

Hnh 3.20. Ca s hon thnh to Database.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

51

* S dng SQL Server Enterprise Manager trn SQL Server 2000 Khi ng SQL Server Enterprise Manager. Chn tn Server v chn Database. Rigth click ln mc Database v chn New Database. Xut hin ca s Database Properties (hnh 3.21).

Hnh 3.21. Ca s Database Properties. + Tab General: Nhp tn Database chng hn QLDiemSV + Tab Data files: t tn cc file d liu, v tr lu tr chng v cc tham s growth. Ch , SQL Server Enterprise Manager t ng to tp tin d liu chnh QLDiemSV_Data (c th thay i c tn) thuc nhm PRIMARY khng th thay i nhm. Ta c th to cc tp tin d liu ph trn cc nhm khc nhau. + Tab Transaction log: Tng t nh trn nhng i vi tp tin ghi cc bn ghi giao dch.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

52

* S dng SQL Server Management Studio ca SQL Server 2005: Nh gii thiu trn, SQL Server Management Studio l cng c tch hp SQL Server Enterprise Manager ca phin bn 2000 nn ta c th s dng to database tng t nh phin bn 2000. Cch to nh sau: 1. M rng cc i tng trn th hin ca SQL trong ca s Object Explorer mun to Database. 2. Right click ln mc Database\ chn New Database xut hin ca s New Database (Hnh 3.22).

Hnh 3.22. Ca s New Database. Trong ca s New Database, ti tab General ta thc hin in cc thng s cho cc mc nh sau: + Database name: in tn Database mun to + Owner: Ch nh tn cc Logins s hu Database ang to. chn cc logins ta click vo nt xut hin ca s Select Database Owner (Hnh 3.23). Trong mc Enter the Object names to select ta nhp tn cc logins hoc chn nt
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

53

Browse lit k v chn cc logins trong ca s Browse for Objects (Hnh 3.24)

Hnh 3.23. Ca s Select Database Owner.

Hnh 3.24. Ca s Browse for Objects. + Database files: Thc hin chn cc thuc tnh cho cc files database, bao gm: o Logical name: Tn logic ca file database. o File Type: Kiu file (Data, Log)

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

54

o Filegroup: Ch nh nhm file. o Initial Size (MB): Kch thc khi to dung lng cc file, tnh theo MB. o Autogrowth: Ch nh cc tham s t ng gia tng dung lng cho cc file. Click vo nt xut hin ca s Change Autogrowth for MyDB (Hnh 3.25) cho php khai bo cc tham s Autogrowth: Ty chn Enable Autogrowth cho php t ng gia tng; File Growth ch nh t ng gia tng theo phn trm (In Percent) hoc theo dung lng ch nh (In Megabytes); Maximum File Size nh ngha gia tng ca file n dung lng ln nht.

Hnh 3.25. Ca s Change Autogrowth for MyDB o Path: Ch nh ng dn vt l lu tr cc files database. Click nt thay i ng dn mc nh.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

55

* S dng T-SQL Ta c th s dng T-SQL hay script to Database, vi cch ny ta cn hiu r v cc c php cu lnh trong SQL Server to Database. CREATE DATABASE database_name [ ON [ PRIMARY ] [ <filespec> [ ,...n ] [ , <filegroup> [ ,...n ] ] [ LOG ON { <filespec> [ ,...n ] } ] ] ] [;] attach mt database:
CREATE DATABASE database_name ON <filespec> [ ,...n ] FOR { ATTACH | ATTACH_REBUILD_LOG } [;] <filespec> ::= { ( NAME = logical_file_name , FILENAME = 'os_file_name' [ , SIZE = size [ KB | MB | GB | TB ] ] [ , MAXSIZE = { max_size [ KB | MB | GB | TB ] | UNLIMITED } ] [ , FILEGROWTH = growth_increment [KB | MB | GB | TB | % ] ] ) [ ,...n ] } <filegroup> ::= { FILEGROUP filegroup_name [ DEFAULT ] <filespec> [ ,...n ] }

Cc tham s trong : database_name: L tn ca CSDL. Nu tn ca file d liu (data file) khng c ch nh th SQL Server s dng database_name l tn cho logical_file_name v os_file_name.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

56

ON Ch nh nh ngha cc file trn a c s dng lu tr cc phn d liu ca database, data files. PRIMARY Ch nh ny lin quan n danh sch nh ngha primary file <filespec>. File u tin c ch nh trong <filespec> ca nhm filegroup primary filegroup tr thnh file primary. Mt database ch c th duy nht mt file primary. Nu t kha PRIMARY khng c ch nh th file u tin trong danh sch cc fie ca cu lnh CREATE DATABASE s tr thnh file primary. LOG ON Ch nh nh ngha file log lu tr trn a, log files. FOR ATTACH Ch nh database c to bng vic attach tp cc file h thng tn ti. FOR ATTACH c cc yu cu sau: Cc files data (MDF v NDF) phi tn ti. Nu nhiu files log tn ti, th tt c phi sn c.

FOR ATTACH_REBUILD_LOG Ch nh database c to bng vic attach tp cc file h thng tn ti. Nu mt hoc nhiu files log giao dch b li th file log s c xy dng li. <filespec> iu khin cc thuc tnh ca file. -

NAME logical_file_name: Ch nh tn logical cho file. NAME c yu cu khi FILENAME c ch nh. FILENAME os_file_name: Ch nh tn, ng dn file h iu hnh (file vt l). SIZE size: Ch nh kch thc file.
B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

Bi ging H qun tr CSDL

57

MAXSIZE max_size: Ch nh kch thc ln nht m file c th pht trin n. T kha UNLIMITED ch nh file c pht trin cho n khi a b y. FILEGROWTH growth_increment: Ch nh t ng gia tng ca file.

<filegroup> iu khin cc thuc tnh ca filegroup.


-

FILEGROUP filegroup_name: Ch nh tn logical ca filegroup. DEFAULT: Ch nh tn filegroup l filegroup mc nh trn database.

V d 3.1. a ra mt cch to Database MyDB vi tp tin d liu chnh l MyDB_Data.mdf, dung lng khi to l 1MB v ti a l 10MB v gia tng kch thc l 10%. Tp tin bn ghi giao dch l MyDB_Log.ldf vi dung lng ban u l 2MB v kch thc ti a khng gii hn, gia tng dung lng l 10MB. to script (dng T- SQL) ta m ca s query son tho: i vi SQL Server 2000: Vo Start/Programs/Microsoft SQL Server/Query Analyzer, xut hin hp thoi Connect to SQL Server, trong danh sch server chn server cc b my mnh v nhp on m lnh sau. i vi SQL Server 2005: Trong ca s SQL Server Management Studio, trn thanh Standard chn nt New Query to ca s truy vn kt ni n th hin SQL ang c kt ni hoc nt Database Engine Query xut hin ca s kt ni (Hnh 3.8) ta thc hin kt ni n th hin SQL m mun thc hin trn . Xut hin ca s truy vn ta thc hin nhp on m lnh sau:
Use master go create database MyDBT On ( Name= MyDBT_Data,

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

58

FileName='E:\Tempt\MyDBT_Data.mdf', Size=10MB, MaxSize=100MB, FileGrowth=10% ) Log On ( Name= MyDBT_log, FileName='E:\Tempt\MyDBT_Log.ldf', Size=2MB, MaxSize=UNLIMITED, FileGrowth=10% )

Click nt Execute hoc F5 chy.

c) Xa Database * Dng Enterprise Manager trong SQL Server 2000: Trong Enterprisse Manager, chn nhm server cc b v m rng mc Database. Sau right click ln CSDL mun xa v chn Delete Database. Xut hin hp thoi xc nhn xa v chn Yes. * S dng SQL Server Management Studio ca SQL Server 2005: xa mt database ta ng nhp vo SQL Server Management Studio vi mt login c quyn xa database v thc hin cc bc sau: 1. M rng cc i tng trn th hin ca SQL trong ca s Object Explorer mun xa Database. 2. M rng mc Database v Right click ln database mun xa v chn Delete xut hin ca s Delete Object chn OK xa. * Dng T-SQL xa Database ta s dng c php sau: DROP DATABASE database_name [ ,...n ] V d: nhp on T-SQL sau xa Database MyDB.
Use master Go Drop Database MyDB Go

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

59

3.2.2.Bng - Table Trc khi i vo cc thao tc i vi bng, ta xt cc kiu d liu c s dng trong SQL Server. a) Cc kiu d liu Kiu d liu bigint binary[(n)] S nguyn 8 byte. D liu nh phn c kch thc c nh n byte. Kch thc lu tr l n+4 byte. Vi 1<n<8000 D liu s nguyn nhn cc gi tr 0, 1 hoc NULL D liu k t, c chiu di n k t, khng h tr Unicode. Vi di 1<n<8000. Tham chiu ti mt con tr. Ch dng cho cc bin v tham s trong stored procedure. D liu ngy gi. Gi tr nhn t 1/1/1753 n 31/12/9999 D liu s thp phn. p l tng s k t s c th c lu, s l s ch s thp phn. D liu s ng c phm vi t -1.79E+308 n 1.79E+308 D liu nh phn c chiu di thay i, di hn 8000 byte v ti a l 2^31-1 byte. D liu s nguyn t -2^31 n 2^31-1. Chim 4 byte. D liu kiu tin t t -2^63 n 2^63. Chim 8byte. D liu k t, c chiu di c nh n k t. C h tr Unicode. Vi 1<n<4000. Chim 2n byte. D liu k t c chiu di thay i, vi chiu di ti a l ngha

bit char[(n)]

cursor

datetime

decimal[(p,[s])] numeric[(p,[s])] float[(n)] image integer hoc int money nchar[(n)] ntext

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

60

2^30-1 k t. H tr unicode. nvarchar[(n)] real smalldatetime smallint smallmoney sql_variant sysname table text timestamp D liu k t c chiu di thay i vi n k t. C h tr Unicode. Vi 1<n<4000. D liu s thc ng, phm vi t - 3.4E+38 n 3.4E+38. Chim 4 byte. D liu ngy gi t 1/1/1900 n 6/6/2079. Chim 4 byte. D liu s nguyn t -2^15 n 2^15-1. Chim 2 byte. D liu kiu tin t t -2^31 n 2^31. Chim 4 byte. Cho php gi cc gi tr ca cc kiu d liu khc nhau (tt c cc kiu d liu h thng khc). y l kiu d liu c bit, do SQL Server nh ngha l kiu nvarchar(128). Chim 256 byte. Tng t nh bng tm, khai bo gm danh sch cc ct v cc kiu d liu. D liu k t c chiu di thay i, di hn 8000byte. C th lu ti 2^31 k t. Khng h tr Unicode. Ct timestamp c cp nht t ng mi khi dng c thm hoc c cp nht. Mi bng ch c th c 1 ct timestamp. Kch thc lu tr l 8 byte. D liu s nguyn t 0 n 255. Chim 1 byte.

tinyint

unique-identifier Gi tr nh phn 16 byte, l s nh danh duy nht ton cc. varbinary[(n)] varchar[(n) D liu nh phn n c chiu di thay i. Vi 1<n<8000 D liu k t c chiu di thay i vi n k t. Khng h tr Unicode. Vi 1<n<4000.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

61

b) To bng. * Dng SQL Server Enterprise Manager trong SQL Server 2000:

Hnh 3.26. Ca s thit Table. Trong Enterprise Manager, m rng danh mc Database v m rng c s d liu QLDiemSV. Right Click ln danh mc Tables, chn New Table. Xut hin ca s thit k bng nh hnh 3.26. Ta thc hin thit k bng HOSOSV gm cc trng (trong ct Column Name), kiu trng (Data Type) v di d liu (Length) v cho php trng nhn gi tr NULL hay khng (Allow Nulls) hnh 3.26. Chn dng MaSV, sau click vo nt Set primary key thit lp trng MaSV l kha. Click vo nt Save, xut hin ca s Choose Name nhp tn bng l HOSOSV lu li bng.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

62

* Dng SQL Server Management Studio trong SQL Server 2005: to bng trong SQL Server Management Studio ta thc hin: 1. M rng cc i tng trn th hin ca SQL trong ca s Object Explorer mun to bng. 2. M rng mc Database v chn c s d liu mun to bng. Right click ln mc Table v chn New Table xut hin ca s thit k table (Hnh 3.27): + Column Name: Nhp tn cc ct trong bng. + Data Type: Chn kiu d liu v di cho kiu. + Allow Nulls: Cho php chp nhn d liu NULL hay khng? + Column Properties: Thit lp cc thuc tnh cho ct ang c chn.

Hnh 3.27. Ca s thit Table trong SQL Server Management Studio . 3. thit lp kha, chn cc trng kha ca bng sau click vo nt biu tng kha (Set Primary Key) hoc right click vo cc trng v chn Set Primary Key.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

63

4. Dng t hp phm Ctrl+S hoc click vo nt Save lu cu trc bng va to trong c s d liu. * Dng T-SQL to bng dng T SQL ta s dng c php sau: CREATE TABLE table_name ( { < column_definition > | < table_constraint > } [ ,...n ] )
< column_definition > ::= { column_name data_type } [ { DEFAULT constant_expression | [ IDENTITY [ ( seed , increment ) ] ] } ] [ < column_constraint > [ ...n ] ] < column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL | NOT NULL ] | [ PRIMARY KEY | UNIQUE ] | REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] } < table_constraint > ::= [ CONSTRAINT constraint_name ] { [ { PRIMARY KEY | UNIQUE } { ( column [ ,...n ] ) } ] | FOREIGN KEY ( column [ ,...n ] ) REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] }

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

64

V d 3.2. To bng a) To bng LOP dng T-SQL.


Use QLDiemSV Go Create Table DMLop (MaLop char(10) NOT NULL, TenLop nvarchar(50) NOT NULL, Khoa char(10) CONSTRAINT PK_DMLOP Primary Key (MaLop))

b) To hai bng MyCustomers v MyOrders. Bng MyCustomers c hai ct, ct CustID va l ct nhn dng IDENTITY[(seed,increment )] c gi tr khi to ban u l 100 v bc nhy l 1 va l kha. Bng MyOrders c kha l OrderID v kha ngoi l CustID tham chiu n bng MyCustomers.
CREATE TABLE MyCustomers (CustID int IDENTITY (100,1) PRIMARY KEY, CompanyName nvarchar (50)) CREATE TABLE MyOrders (OrderID int PRIMARY KEY, CustID int REFERENCES MyCustomers(CustID))

c) Thay i cu trc bng * Dng SQL Server Enterprise Manager trong SQL Server 2000: + Trong Enterprise Manager, m rng danh mc Database, m rng c s d liu c bng cn thay i cu trc, chng hn QLDiemSV v chn mc Table. + Right Click ln bng thuc CSDL QLDiemSV cn thay i cu trc, chn Design Table. Xut hin ca s thit k bng nh hnh 3.26. Ta thc hin cc thay i v cu trc: i kiu d liu, thm trng, xa trng, thit lp kha .v.vvi bng chn . * Dng SQL Server Management Studio trong SQL Server 2005: thay i cu trc bng trong SQL Server Management Studio ta thc hin cc bc sau:

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

65

+ M rng cc i tng trn th hin ca SQL trong ca s Object Explorer mun thay i cu trc bng. + M rng mc Database v chn c s d liu v bng cn thay i cu trc. Right click ln bng v chn Modify xut hin ca s thit k table (Hnh 3.27) v ta thc hin cc thay i i vi cu trc bng nh cch to bng. * Dng T-SQL thay i cu trc bng bng T-SQL ta c c php cu lnh sau:
ALTER TABLE table_name { ALTER COLUMN column_name { type_name [ ( { precision [ , scale ] | max } ) ] [ NULL | NOT NULL ] } | [ WITH { CHECK | NOCHECK } ] ADD { <column_definition> | <computed_column_definition> | <table_constraint> } [ ,...n ] | DROP { [ CONSTRAINT ] constraint_name | COLUMN column_name } [ ,...n ] | [ WITH { CHECK | NOCHECK } ] { CHECK | NOCHECK } CONSTRAINT { ALL | constraint_name [ ,...n ] } | { ENABLE | DISABLE } TRIGGER { ALL | trigger_name [ ,...n ] } [ ; ]

V d 3.3. Thay i cu trc bng MyCustomers


ALTER TABLE MyCustomers ADD CustType CHAR(10) NULL

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

66

d) Nhp d liu cho bng * Dng Enterprise Manager Trong Enterprise Manager, m rng danh mc Database, m rng c s d liu QLDiemSV v chn mc Table. Right Click ln bng thuc CSDL QLDiem cn nhp d liu, chn Open Table\Return all row. Xut hin ca s nhp d liu cho bng . * Dng SQL Server Management Studio trong SQL Server 2005: + M rng cc i tng trn th hin ca SQL trong ca s Object Explorer mun nhp d liu cho bng. + M rng mc Database, chn c s d liu v bng cn nhp d liu. Right click ln bng cn nhp d liu v chn Open Table xut hin ca s nhp d liu cho bng. * Dng T-SQL V d 3.3. Chn d liu vo bng LOP Chn mt bn ghi:
Insert Into LOP(MaLop, TenLop, Khoa) VALUES ('TH6A',N'Tin hc 6A', '6')

Chn tt c cc bn ghi t bng DMLOP vo bng LOP.


Insert Into LOP(MaLop, TenLop, Khoa) Select MaLop, TenLop, Khoa From DMLOP

e) Xa bng * Dng Enterprise Manager Trong Enterprise Manager, m rng danh mc Database, m rng c s d liu QLDiemSV v chn mc Table. Right Click ln bng cn xa, chn Delete. * Dng SQL Server Management Studio trong SQL Server 2005: + M rng cc i tng trn th hin ca SQL trong ca s Object Explorer mun xa bng.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

67

+ M rng mc Database, chn c s d liu cha bng mun xa. Right click ln bng mun xa v chn Delete xut hin ca s xc nhn thng tin xa, chn OK. * Dng T-SQL
DROP TABLE DMLOP

3.2.3. View a) Khi nim View View l mt bng o c nh ngha bi mt truy vn vi pht biu SELECT. View c hnh thnh d liu t mt hoc nhiu bng tht. i vi ngi s dng th view ging nh mt bng tht. b) To view to View trong SQL Server 2000 , ta c 3 cch khc nhau to: + S dng Create View Wizard + SQL Server Enterprise Manager + Dng T-SQL Trong SQL Server 2005 , ta c 2 cch khc nhau to: + SQL Server Management Studio + Dng T-SQL * Dng Enterprise Manager hoc Management Studio Trong Enterprise Manager hoc Management Studio, m rng danh mc Database, m rng c s d liu mun to view, chng hn CSDL QLDiemSV v chn mcViews. Right Click ln danh mc Views, chn New View. Xut hin ca s thit k view nh hnh 3.28 i vi SQL Server 2000 v hnh 3.29 i vi SQL Server 2005, gm 4 vng sau:

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

68

Hnh 3.28. Ca s thit k view trn SQL Server 2000.

Hnh 3.29. Ca s thit k view trn SQL Server 2005. + Diagram pane: Hin th d liu ngun c th l cc bng, cc view khc, functions to view. Cc ct d liu ca view c chn t vng ny.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

69

+ Grid pane (Criteria pane): Hin th cc ct ca view c chn t vng diagram. + SQL pane: Hin th pht biu SQL dng nh ngha view. + Results pane: Hin th kt qu nhn c t view. Ta c th n hoc hin cc ca s ny bng cch click vo cc nt tng ng trn thanh cng c ca ca s thit k view. Danh sch sau th hin ngha ca cc nt trn thanh cng c tnh t tri sang phi: i vi SQL Server 2000: + Save: Lu view. + Properties: Cho php thay i thuc tnh ca view. + Show hide pane: cc nt n hoc hin cc ca s trn. + Run: Thc thi v hin th kt qu ca view trong Results pane. + Cancel Execution And Clear Results: Xa Results pane. + Verify SQL: Kim tra c php ca pht biu SQL. + Remove Filter: loi b tt c cc lc d liu c nh ngha. + Use GROUP BY: Thm mnh group by trong cu lnh SQL. + Add Table: Thm cc bng, view lm ngun d liu cho view mi. i vi SQL Server 2005: + Show Diagram pane: n hoc hin ca s Diagram pane. + Show Criteria pane: n hoc hin ca s Criteria pane. + Show SQL pane: n hoc hin ca s SQL pane. + Show Results pane: n hoc hin ca s kt qu. + Execute SQL: Thc hin truy vn. + Verify SQL Syntax: Kim tra c php cu lnh SQL. + Add Group By: Thm mnh group by trong cu lnh SQL.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

70

+ Add Table: Thm cc bng, view, hm lm ngun d liu cho view mi. Click vo nt Add Table, xut hin hp thoi Add Table chn cc bng cc view lm ngun d liu cho view mi. Trong v d ta chn bng HOSOSV v LOP. Sau khi chn ngun d liu ta thc hin chn cc trng lm d liu trn view nh hnh 3.30 (SQL Server 2000 ) v 3.31 (SQL Server 2005) Click vo nt Save, xut hin hp thoi Save lu vi tn Danhsach.

Hnh 3.30. Ca s thit k view Danhsach trong SQL Server 2000 .

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

71

Hnh 3.31. Ca s thit k view Danhsach trong SQL Server 2005. S dng vng Grid Pane (Criteria) h tr cho vic thit k View: + Ct Column: Cha tn cc trng trong bng\view lm ngun d liu cho truy vn ny hoc cha mt biu thc nh ngha mt trng mi cho view. + Ct Alias: Ch nh b danh cho trng trong view mi. + Ct Table: Ch nh ngun d liu. + Ct Output: Ch nh hin th hay khng hin th trng . + Ct Sort Type v Sort Order: Dng sp xp d liu. + Ct Criteria: Dng t iu kin lc cho cc bn ghi. + Cc ct Or: Dng kt hp vi ct Criteria to cc iu kin lc d liu phc tp. Tnh tng trong truy vn: tnh tng trong truy vn dng vng Grid Pane ta c th tin hnh phn nhm cc bn ghi v thc hin tnh ton trn tng phn nhm . tnh tng trong truy vn ta chn nt Use Group By

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

72

xut hin ct Group By trong vng Grid Pane. Ta thc hin tin hnh phn cc nhm trng nh sau: + Trng lm iu kin, tiu chun tham gia phn nhm v tnh tng: Chn Where trong ct Group By v t biu thc iu kin trong ct Creteria. + Trng phn nhm: Chn Group by trong ct Group By. + Trng tnh ton: Chn mt hm c sn (sum, count, avg, max, min, .v.v...) trong ct Group By hoc xy dng mt biu thc tnh ton trong ct Column. + nh tiu chun hin th kt qu: t iu kin ct Criteria ti cc trng phn nhm v trng tnh ton. + Chn th t hin th: Dng ct Sort Type v Sort Order ti cc cc trng phn nhm v cc trng tnh ton. * Dng Create view wizard Khi ng SQL Server Enterprise Manager, chn tn server cc b v vo menu Tools\Wizards. Xut hin ca s Select Wizard hnh 3.5. Chn Create View Wizard xut hin ca s Welcometo the Create View Wizard, nh hnh 3.32. Chn Next. Xut hin ca s Select Database (Hnh 3.33) chn CSDL m view c to trn . Chn Next. Trong ca s Select Objects chn cc bng lm ngun d liu cho View mi (Hnh 3.34). Chn Next. Chn cc ct d liu ca view (hnh 3.35). Ca s tip theo (hnh 3.36): t iu kin lc tng t nh mnh WHERE trong khi cu lnh SELECT. Chn Next. Chn tn view (hnh 3.37) v chn Finish (hnh 3.38) kt thc.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

73

Hnh 3.32.Ca s Welcometo the Create View Wizard.

Hnh 3.33.Ca s Select Database.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

74

Hnh 3.34.Ca s Select Objects.

Hnh 3.35.Ca s Select Columns.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

75

Hnh 3.36.Ca s Define Restriction

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

76

Hnh 3.37.Ca s Define Restriction

Hnh 3.38.Ca s Define Restriction

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

77

* Dng T-SQL: Ta dng c php cu lnh sau: CREATE VIEW [schema_name.]view_name[(column[,...n])] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ ; ] [ WITH CHECK OPTION ] <view_attribute> ::= { [ ENCRYPTION ] [ SCHEMABINDING ] [ VIEW_METADATA ] Trong : schema_name L tn ca lc m view thuc lc . view_name L tn ca view. column L tn c s dng cho mt ct trong view. Tn mt ct ch yu cu khi ct c sinh ra t mt biu thc i s, mt hm, mt hng; khi hai hoc nhiu ct khc nhau c cng tn, in hnh l trong lin kt; hoc khi mt ct trong view c ch nh tn khc vi tn t ngun d liu. Cc tn ct c th c gn trong cu lnh SELECT. Nu ct khng c ch nh trong view th cc ct trong view c tn cng tn vi cc ct cu lnh SELECT. select_statement L cc khi cu lnh SELECT nh ngha view. Cc khi cu lnh SELECT c phn cch nhau bi mnh UNION hoc UNION ALL. Mt Index c nh ngha trn view i hi view phi c xy dng t mt bng n hoc nhiu bng lin kt nhau trong t hp ty chn.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

78

CHECK OPTION Bt buc tt cc cu lnh sa i d liu thc hin trn view phi tun theo cc iu kin trong khi cu lnh select_statement. ENCRYPTION M ha bn text ca cu lnh CREATE VIEW trong sys.syscomments. Vic s dng WITH ENCRYPTION ngn cn view b cng b nh l mt phn bn sao SQL Server. SCHEMABINDING Buc view vo mt lc di mt bng hoc nhiu bng. Khi SCHEMABINDING c ch nh, bng hoc cc bng c c khng c sa trong nhng cch nh hng n nh ngha view. VIEW_METADATA Ch nh cc th hin SQL Server s tr v cho DB-Library, ODBC, v OLE DB APIs thng tin siu d liu v view, thay cho bng v cc bng c s khi trnh duyt siu d liu c yu cu cho mt truy vn tham chiu n view. V d 3.4. Trong CSDL Northwind c hai bng Orders v Order Details. Ta xy dng view tnh tng gi tr cho tng ha n (SQL Server 2000). Create View TongGT as SELECT dbo.Orders.OrderID, SUM(dbo.[Order Details].UnitPrice * dbo.[Order Details].Quantity) AS Tolal FROM dbo.Orders INNER JOIN dbo.[Order Details] ON dbo.Orders.OrderID = dbo.[Order Details].OrderID GROUP BY dbo.Orders.OrderID Go

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

79

c) Thay i view * Dng Enterprise Manager Trong Enterprise Manager, m rng danh mc Database, m rng c s d liu mun to view, chng hn CSDL QLDiemSV v chn mcViews. Right Click ln View, chn Design View. Xut hin ca s thit k view. Thc hin cc thay i trn view v ghi li cc thay i . * Dng SQL Server Management Studio Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu mun to view, chng hn CSDL QLDiemSV v chn mcViews. Right Click ln View, chn Modify. Xut hin ca s thit k view. Thc hin cc thay i trn view v ghi li cc thay i . * Dng T-SQL: Ta dng c php cu lnh sau ALTER VIEW [schema_name.]view_name [(column[,...n])] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ ; ] [ WITH CHECK OPTION ] <view_attribute> ::= {[ENCRYPTION][SCHEMABINDING][VIEW_METADATA] } V d 3.5. Sa i view DSSV nh sau:
ALTER VIEW DSSV AS Select MaSV, Hodem + ' '+ TenSV AS Hoten, Ngaysinh From HosoSV GO Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

80

d) Xa view - Trong ca s Enterprise Manager, m rng danh mc Database, m rng c s d liu mun xa view, chng hn CSDL QLDiemSV v chn mcViews. Sau right click ln View mun xa, chn Delete. - Trong ca s SQL Server Management Studio, m rng danh mc Database, m rng c s d liu mun xa view, chng hn CSDL QLDiemSV v chn mcViews. Sau right click ln View mun xa, chn Delete xut hin ca s xc nhn xa chn OK. - Dng T-SQL dng lnh DROP VIEW theo c php: DROP VIEW view_name V d 3.6. Xa view DSSV nh sau:
DROP VIEW DSSV

3.2.4. Ch mc - Index a) Khi nim ch mc Ch mc l mt trong nhng cng c mnh c sn i vi ngi thit k CSDL. Mt ch mc l mt cu trc ph cho php ci thin hiu sut thc thi cc truy vn bng cch gim thiu cc hot ng nhp/xut d liu cn thit c d liu yu cu. Ty thuc vo kiu ca n, m ch mc c lu vi d liu hoc tch bit vi d liu. - Ch mc kha: Ch mc kha ch d ct hoc cc ct c dng sinh ra ch mc. N cho php tm nhanh chng dng d liu mun tm. truy cp dng d liu dng ch mc, ta ch cn a ra gi tr kha ca ch mc hoc a cc gi tr vo mnh WHERE trong khi cu lnh SELECT. - Ch mc duy nht: L ch mc ch cha mt dng d liu cho mi kha ch mc. Mt ch mc l duy nht nu bn thn d liu l duy nht, nu khng duy nht ta c th to ch mc kt hp trn nhiu ct t c ch mc duy nht. - Cc kiu ch mc: Cc ch mc c lu tr d liu di dng cy nh phn B-Tree. C hai kiu ch mc

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

81

Ch mc lin cung (clustered): L ch mc lu tr cc dng d liu thc s ca bng trong nt l, theo th t c sp xp. Ch mc phi lin cung (Nonclustered): Khng cha d liu trong nt l, m n cha thng tin v v tr ca dng d liu: nu khng c ch mc lin cung trn bng th n cha s nhn dng dng (Row ID); nu c ch mc lin cung th trong nt l ny s cha gi tr kha ch mc lin cung cho d liu . Ch : Indexes c to t ng khi cc rng buc PRIMARY KEY v UNIQUE c nh ngha trn cc ct ca bng b) To ch mc to Indexes trong SQL Server 2000 , ta c 3 cch khc nhau to: + S dng Create View Wizard + SQL Server Enterprise Manager + Dng T-SQL Trong SQL Server 2005, ta c 2 cch khc nhau to: + SQL Server Management Studio + Dng T-SQL * Dng wizard Khi ng SQL Server Enterprise Manager, chn tn server cc b v vo menu Tools\Wizards. Xut hin ca s Select Wizard hnh 3.5. Chn Create Index Wizard xut hin ca s Welcometo the Create Index Wizard, nh hnh 3.39. Chn Next. Xut hin ca s Select Database and Table (hnh 3.40). Chn CSDL v bng d liu cn to index. + Mc Database name: Chn c s d liu + Mc Object name: Chn bng d liu

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

82

Sau chn Next. Xut hin ca s Current index information (hnh 3.41) a thng tin cc Index c to trc . Ca s tip theo l ca s Select columns (hnh 3.42). Trong ca s ny ta chn cc ct to ch mc. Chn Next. Xut hin ca s Specify Index Option (hnh 3.43). Ch nh cc tham s cho Index nh: To ch mc duy nht, ti u,.v.v. Chn Next. Xut hin ca s Completing the Create Index Wizard (hnh 3.44). Chn th t, t tn cho Index. Cui cng chn Finish kt thc.

Hnh 3.39.Ca s Welcometo the Create Index Wizard.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

83

Hnh 3.40.Ca s Select Database and Table.

Hnh 3.41.Ca s Current index information.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

84

Hnh 3.42.Ca s select columns.

Hnh 3.43. Ca s Specify Index Option.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

85

Hnh 3.44. Ca s Completing the Create Index Wizard

* Dng Enterprise Manager: Trong ca s Enterprise Manager, m rng danh mc Database, m rng c s d liu mun to Index, chng hn CSDL QLDiemSV v chn mc Tables. Sau right click ln bng mun to ch mc. Chn All Task\Manage Indexes. Xut hin ca s Manage Indexes nh hnh 3.45. Trong ca s ny chn CSDL trong mc Database, chn bng hoc View trong mc Table/view v sau click nt New xut hin ca s Create New Index hnh 3.46. Trong ca s ny ta nhp tn ca Index trong mc Index name v chn cc trng ca Index trong ct Column.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

86

Hnh 3.45. Ca s Manage Indexes

Hnh 3.46. Ca s Create New Index


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

87

Ngoi ra, trong ca s 3.45 Manage Indexes ta c cc nt thao tc qun l ch mc (Index): o Nt New: Dng thm mt Index mi. o Nt Edit: Chn Index c trong danh sch v chn nt Edit thc hin chnh sa ch mc c. o Nt Delete: Chn Index c trong danh sch v chn nt Delete thc hin xa ch mc chn. * Dng SQL Server Management Studio Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu cha bng hoc view mun to ch s.

Hnh 3.47. Ca s New Index

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

88

M rng mc Table hoc View, m rng bng hoc view mun to Index. Right Click ln th mc Indexes chn New Index, xut hin ca s New Index nh hnh 3.47. gm cc tham s: + Table name (hoc View name i vi view): Tn bng (hoc tn view) m tp ch s c xy dng trn . + Index name: t tn tp ch s mun xy dng. + Index type: Kiu ca index (Clustered, Nonclustered) + Unique: Ty chn cho php to tp ch s ny c l tp ch s duy nht hay khng? + Index key columns: Xc nh cc trng kha ca index bng cch click nt Add xut hin ca s Select Columns Hnh 3.48, ta chn cc ct lm kha cho Index.

Hnh 3.48. Ca s Select Columns Ch : Trong SQL Server 2005, chng ta c th m rng chc nng ca cc tp ch s phi lin cung (nonclustered indexes) bng cch thm cc ct khng l kha (nonkey columns) vo cc nt l ca cy nonclustered index. Cc ct kha c lu tr ti tt c cc mc cn cc ct khng kha ch lu tr ti mc l ca index. Bng vic thm cc ct khng kha, ta c th to cc
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

89

tp ch s phi lin cung ph nhiu truy vn hn bi v cc ct khng kha c cc li ch sau: + Chng c th l cc ct c kiu d liu khng c php lm cc ct kha trong index.
+ Chng khng c Database Engine xt khi tnh n s cc ct

kha ca Index hay kch thc kha ca index. Mt index c bao gm tt c cc ct khng kha c th ci thin ng k s thc thi truy vn khi tt c cc ct trong c bao gm trong index (c cc ct kha v khng kha ca index). thm cc ct khng kha ta chn trang Included Columns (Hnh 3.49). Sau click nt Add xut hin ca s Select Columns (Hnh 3.48).

Hnh 3.49. Ca s New Index

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

90

* Dng T - SQL - Trn SQL Server 2000:


CREATE [ UNIQUE][CLUSTERED|NONCLUSTERED]INDEX index_name ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) [ WITH < index_option > [ ,...n] ] [ ON filegroup ] < index_option > :: = { PAD_INDEX | FILLFACTOR = fillfactor | IGNORE_DUP_KEY | DROP_EXISTING | STATISTICS_NORECOMPUTE | SORT_IN_TEMPDB }

- Trn SQL Server 2005:


CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name ON <object> ( column [ ASC | DESC ] [ ,...n ] ) [ INCLUDE ( column_name [ ,...n ] ) ] [ WITH ( <relational_index_option> [ ,...n ] ) ] [ ON { filegroup_name|default } ] [ ; ] <object> ::= { [ database_name. [ schema_name ] . | schema_name. ] table_or_view_name } <relational_index_option> ::= { PAD_INDEX = { ON | OFF } | FILLFACTOR = fillfactor | SORT_IN_TEMPDB = { ON | OFF } | IGNORE_DUP_KEY = { ON | OFF } | STATISTICS_NORECOMPUTE = { ON | OFF } | DROP_EXISTING = { ON | OFF } | ONLINE = { ON | OFF } | ALLOW_ROW_LOCKS = { ON | OFF } | ALLOW_PAGE_LOCKS = { ON | OFF } | MAXDOP = max_degree_of_parallelism }
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

91

Cc tham s trong : UNIQUE Ch nh to mt unique index trn bng hoc trn view. Mt clustered index trn view buc phi l unique. CLUSTERED Ch nh to ch mc lin cung. NONCLUSTERED Ch nh to ch mc phi lin cung. Mc nh l ch mc NONCLUSTERED. index_name L tn ca tp ch s. column L tn ct hoc cc ct m index da trn . INCLUDE ( column [ ,... n ] ) Ch nh cc ct khng kha c thm vo mc l ca ch mc phi lin cung. ON filegroup_name To index trn filegroup ch nh. Nu khng c ch nh ny th index s dng cng filegroup m table hoc view da trn. ON "default" To index da trn filegroup mc nh. V d 3.7. To Index trn bng LOP ca CSDL QLDiemSV
Use QLDiemSV create Unique index indTenLopind On LOp(TenLop)

V d 3.8. Xy dng li Index TenLop_ind trn bng LOP ca CSDL QLDiemSV


Use QLDiemSV create Unique index TenLop_ind On LOp(TenLop) With DROP_EXISTING

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

92

V d 3.9. Dng t kha DBCC DBREINDEX Use QLDiemSV Go DBCC DBREINDEX(HOSOSV) c) Loi b ch mc + Dng Enterprise Manager: Trong ca s Enterprise Manager, m rng danh mc Database, m rng c s d liu mun xa Index, chng hn CSDL QLDiemSV v chn mc Tables. Sau right click ln bng mun to ch mc. Chn All Task\Manage Indexes. Xut hin ca s Manage Indexes nh hnh 3.45. Chn Index mun xa v chn Delete. + Dng SQL Server Management Studio: Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu cha bng hoc view mun xa ch s. M rng mc Indexes ca bng hoc view , right click ln Index mun xa v chn Delete. + Dng lnh T-SQL: DROP INDEX <table.index> | <view.index> Ch : i vi SQL Server 2005 ta c th s dng c php sau: DROP INDEX index_name ON <Table|View> V d 3.10. Loi b ch mc TenLop_ind
Use QLDiemSV Go DROP INDEX Lop. indTenLop Go

d) Full Text Index Full Text Indexes c s dng trong SQL Server thc hin vic tm tim ton vn (Full Text Searches). Ta s dng t kha LIKE trong cc truy vn tm kim. Full Text Indexing l mt c im ca SQL Server 2005 cho php cc cu truy vn phc tp c thc thi trn d liu kiu k t.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

93

S dng Full Text Indexing thc hin tm kim theo tng t, hai hoc nhiu t lin nhau, theo on hay cc phn ca t. Vic s dng Full Text Indexing tm kim rt hu dng khi d liu c biu din bi mt nh dng khng cu trc. Khi cu truy vn Full Text c thc hin, b my tm kim tr v cc gi tr kha m so khp vi iu kin tm kim. i tng ci t Full Text Searching l Full Text Index v Full Text Catalog. + Full Text Index theo di cc t c ngha trong bng. Index ny c s dng cho cc tm kim cha cc t ch mc v cc la chn tm kim cao cp, chng hn nh cc nhm tm kim. Mt Full Text Index yu cu mt ct cha cc gi tr kha duy nht. Cc Full Text Indexes khng t ng cp nht khi c s thay i d liu trn bng m ta phi thc hin Update th cng. + Full Text Catalog: Tt c cc Full Text Indexes c lu tr trong cc Full Text Indexing. Mt Full Text Catalog l mt th mc c th c view bi window v Search Service. Theo mc nh tt c cc Full Text Indexes ca mt CSDL cha trong mt Full Text Catalog, tuy nhin ngi qun tr h thng c th chia catalog thnh nhiu catalogs khi cc indexes qu ln. * To Full Text Index: Ch c mt Full Text Index c to trn mt bng, tuy nhin ta c th index nu c th c to trn s kt hp ca nhiu ct. To full text index bao gm hai bc: Full Text Catalog v Full Text index. + S dng Management Studio: o To Full Text Catalog: Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu cha bng mun to full text index v m rng mc Storage. Right click ln mc Full Text Catalogs/ chn New Full Text Catalog xut hin ca s New Full Text Catalog (Hnh 3.50), thc hin in cc tham s tn v v tr lu tr catalog.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

94

Full text catalog name: Tn ca Full text catalog. Catalog location: V tr lu file.

Hnh 3.50. Ca s New Full text catalog o To Full Text Index: Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu cha bng mun to full text index. Right click trn bng mun to v chn Full Text Index\ Define Full Text Index, xut hin ca s Welcome to SQL Server Full Text Indexing Wizard (Hnh 3.51). Tip theo thc hin theo cc ch dn ca cc ca s wizard (Hnh 3.51-Hnh 3.58).

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

95

Hnh 3.51. Ca s Welcome to SQL Server Full Text Indexing Wizard

Hnh 3.52. Ca s Select an Index

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

96

Hnh 3.53. Ca s Select Table Columns

Hnh 3.54. Ca s Select Change Tracking

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

97

Hnh 3.55. Ca s Select a Catalog

Hnh 3.56. Ca s Define Population Schedules

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

98

Hnh 3.57. Ca s Full Text Indexing Wizard Description

Hnh 3.58. Ca s Full Text Indexing Wizard Progress

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

99

+ S dng T SQL: CREATE FULLTEXT CATALOG catalog_name [IN PATH 'rootpath'] [AS DEFAULT] CREATE FULLTEXT INDEX ON table_name [(column_name [,...n])] KEY INDEX index_name [ON fulltext_catalog_name] ] Trong :
catalog_name: L tn ca catalog rootpath: Ch nh th mc gc cha catalog. Nu khng ch nh th

mc ny th s l th mc mc nh khi ci t SQL Server.


AS DEFAULT : Ch nh catalog ny l catalog mc nh. table_name: Tn bng to Full Text Index. column_name: Tn ct hoc cc ct c cha trong full text index,

ch c cc ct kiu char, varchar, nchar, nvarchar, text, ntext, image, xml, v varbinary c th c cha trong full-text search.
index_name: L tn ca mt key index dng unique trn table_name.

KEY INDEX phi l unique, single-key, non-nullable

column. Nn chn key index unique nh nht cho full-text unique key, tt nht chn mt CLUSTERED index.
fulltext_catalog_name: Tn ca full text catalog cha full text

index ang to. V d 3.11. To full text catalog v full text index
USE AdventureWorks; GO CREATE UNIQUE INDEX ui_ukJobCand ON HumanResources.JobCandidate(JobCandidateID); CREATE FULLTEXT CATALOG ft AS DEFAULT; CREATE FULLTEXT INDEX ON HumanResources.JobCandidate(Resume) KEY INDEX ui_ukJobCand;

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

100

V d 3.12. To full text catalog v full text index


CREATE FULLTEXT CATALOG [CatalogNorthwind] IN PATH N'E:\BaiGiang\BaiGiang_HQTCSDL\DATA' WITH ACCENT_SENSITIVITY = ON AUTHORIZATION [dbo] Create fulltext index on products (ProductName, QuantityPerUnit) KEY INDEX PK_Products ON Products

* Sa Full Text Index: Dng Management Studio hoc dng T-SQL + ALTER FULLTEXT CATALOG catalog_name { REBUILD | REORGANIZE | AS DEFAULT }

Trong :
REBUILD: Ch nh xy dng li ton b catalos bng cch xa catalog

c v to li catalog mi.
REORGANIZE: Ch nh kt hp cc ch mc nh thnh trong tin trnh

lp ch mc thnh mt ch mc ln hn.
AS DEFAULT : Ch nh catalog ny l catalog mc nh.

ALTER FULLTEXT INDEX ON table_name { ENABLE | DISABLE | ADD (column_name) | DROP (column_name [,...n] ) }

Trong :
ENABLE|DISABLE: Ch nh SQL Server c hoc khng thu thp d

liu full text index cho table_name, ENABLE kch hot cn DISABLE tt .
ADD|DROP: Thm hoc xa cc ct.

* Xa Full Text Index: Dng Management Studio hoc dng T-SQL DROP FULLTEXT CATALOG catalog_name DROP FULLTEXT INDEX ON table_name V d 3.13. Xa full text catalog v full text index
IF EXISTS (SELECT * FROM sysfulltextcatalogs ftc WHERE ftc.name = N'CatalogNorthwind') DROP FULLTEXT CATALOG [CatalogNorthwind] Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

101

* Tm kim vi Full Text Index: Trong mnh WHERE ca khi cu lnh SELECT ta s dng cc t kha CONTAINS hoc FREETEXT thc hin tm kim. T kha CONTAINS: S dng t kha ny thc hin tm kim cho + Mt t hoc cm t. + Tin t ca mt t hoc cm t. + Mt t gn t khc. + Mt t l bin t ca t khc (V d: drive c cc bin t drives, drove, driving, v driven). + Mt t ng ngha vi cc t khc, s dng t in ng ngha (V d t metal (Ting Anh) ng ngha vi cc t aluminum v steel). C php: CONTAINS ( {column_name|(column_list)|* } , '< contains_search_condition >') < contains_search_condition > ::= { < simple_term > | < prefix_term > | < generation_term > | < proximity_term > | < weighted_term > }
| { ( < contains_search_condition > ) [ { < AND > | < AND NOT > | < OR > } ] < contains_search_condition > [ ...n ] } < simple_term > ::= word | " phrase " < prefix term > ::= { "word * " | "phrase *" } < generation_term > ::= FORMSOF ({INFLECTIONAL|THESAURUS},<simple_term>[ ,...n ] ) < proximity_term > ::= {<simple_term>|<prefix_term>} { { NEAR | ~ }{<simple_term >|<prefix_term>}}

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

102

<

< < <

[ ...n ] weighted_term > ::= ISABOUT ( { { < simple_term > | < prefix_term > | < generation_term > | < proximity_term > } [ WEIGHT ( weight_value ) ] } [ ,...n ] ) AND > ::= { AND | & } AND NOT > ::= { AND NOT | & !} OR > ::= { OR | | }

V d 3.13. Tm kim s dng CONTAINS


USE AdventureWorks; GO SELECT Name, ListPrice FROM Production.Product WHERE ListPrice = 80.99 AND CONTAINS(Name, 'Mountain'); SELECT Name FROM Production.Product WHERE CONTAINS(Name, '"Mountain Frame"OR"Road" ') SELECT Name FROM Production.Product WHERE CONTAINS(Name, ' "Chain*" '); SELECT Description FROM Production.ProductDescription WHERE CONTAINS(Description, 'bike NEAR performance'); SELECT Description FROM Production.ProductDescription WHERE CONTAINS(Description, ' FORMSOF (INFLECTIONAL, ride) '); SELECT Description FROM Production.ProductDescription WHERE CONTAINS(Description, 'ISABOUT (performance weight (.8),comfortable weight (.4), smooth weight (.2) )' );
GO

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

103

USE AdventureWorks; GO DECLARE @SearchWord varchar(30) SET @SearchWord ='Performance' SELECT Description FROM Production.ProductDescription WHERE CONTAINS(Description, @SearchWord); GO

T kha FREETEXT: Thc hin tm kim i vi cc kiu d liu k t, so khp theo ngha khng nht thit phi chnh xc theo t ca chui tm kim. Khi FREETEXT c s dng, b my tm kim thc thi cc hnh ng sau trn chui tm kim: gn cho mi t mt trng s sau mi so khp. + Chia chui tm kim thnh tng t. + Sinh cc bin t ca cc t . + Nhn dng danh sch m rng hoc thay th cc mc ng ngha trong chui so khp. C php: FREETEXT({column_name |(column_list) | * }, 'freetext_string' )

V d 3.14. Tm kim s dng FREETEXT


USE AdventureWorks; GO DECLARE @SearchWord varchar(30); SET @SearchWord ='Install'; SELECT Title FROM Production.Document WHERE FREETEXT(Title, @SearchWord);

3.2.5. Lc - Diagrams a) To lc * Dng Enterprise Manager: Trong Enterprise Manager, m rng danh mc Database, m rng c s d liu mun to lc , chng hn CSDL QLDiemSV v chn mc Diagrams.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

104

Right Click ln Diagrams, chn New Database Design. Xut hin ca s Wellcome to Create Database Wizard (Hnh 3.50). Chn Next. Xut hin ca s Ca s Select Tables to be Added (hnh 3.51). Chn cc bng s dng xy dng lc quan h. Chn Next. Ca s Completing the Create Database Wizard (hnh 3.52) chn Finish. Xut hin ca s thit k Diagrams (hnh 3.53). Trong ca s ny ta thc hin thit k cc mi quan h gia cc bng bng cch: Ko v gi chut trn trng quan h ca bng ny sau nh vo trng quan h ca bng kia. Xut hin ca s Relationship (hnh 3.54). Trong ca s ny ta chn trng quan h gia hai bng v cc iu kin cho mi quan h ang to gia hai bng ny.

Hnh 3.50. Ca s Wellcome to Create Database Wizard

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

105

Hnh 3.51. Ca s Select Tables to be Added

Hnh 3.52. Ca s Completing the Create Database Wizard

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

106

Hnh 3.53. Ca s thit k Diagrams

Hnh 3.54. Ca s Create Relationship

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

107

* Dng SQL Server Management Studio Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu mun to Database Diagrams. Right click v chn New Database Diagram xut hin ca s Add Table hnh 3.55.

Hnh 3.55. Ca s Add Table Chn cc bng xy dng lc thng qua nt Add. Xut hin ca s thit k Diagram (Hnh 3.56). Ta thc hin thit k mi quan h gia cc bng trong c s d liu bng vic ko v gi trng ca bng ny th sang trng tng ng ca bng khc xut hin ca s Table and Columns (Hnh 3.57). Ta thc hin iu chnh cc tham s cho mi quan h .

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

108

Hnh 3.56. Ca s thit k Diagram

Hnh 3.57. Ca s thit k Table and Columns

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

109

b) Chnh sa lc * S dng Enterprise Manager: Trong Enterprise Manager, m rng danh mc Database, m rng c s d liu mun to lc , chng hn CSDL QLDiemSV v chn mc Diagrams. Double Click ln lc mun chnh sa. Xut hin ca s Edit Diagram (Hnh 3.53). Ta thc hin cc thao tc chnh sa lc trn ca s ny: + Thm bng mi: Right click v chn Add table + Xa bng: Right click ln bng xa v chn Remove Table from Diagram. + Xa quan h: Right click ln quan h mun xa v chn Delete Relationship from Database. + Chnh sa li quan h: Right click ln quan h mun chnh sa v chn Properties. Thc hin cc chnh sa trn ca s ny. * Dng SQL Server Management Studio Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu sa i Database Diagrams. Right click vo Diagram mun sa i v chn Modify xut hin ca s thit k Database Diagram nh hnh 3.56 ta thc hin sa i trn ca s ny. c) Xa lc * S dng Enterprise Manager: Trong Enterprise Manager, m rng danh mc Database, m rng CSDL v chn mc Diagrams. Right click ln lc mun xa v chn Delete. * Dng SQL Server Management Studio Trong SQL Server Management Studio, m rng danh mc Database, m rng c s d liu sa i Database Diagrams. Right click vo Diagram mun sa i v chn Delete xut hin ca s xc nhn xa v chn OK.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

110

3.3. BO M D LIU TRONG SQL SERVER 3.3.1. Phn quyn v bo mt trong SQL Server 3.3.1.1. To v qun l ngi dng a) Cc ch xc thc truy cp vo SQL Server ta dng hai ch xc thc: Xc thc thng qua h iu hnh: Vi kiu xc thc ny, SQL Server da vo Windows NT/2000 cp bo mt ng nhp. Khi ngi dng ng nhp vo Windows NT/2000, s nh danh ti khon ngi dng c kim tra s hp l. SQL Server tch hp qu trnh bo mt ng nhp ca n vi qu trnh bo mt ng nhp ca Windows cung cp nhng dch v ny. Khi ngi dng xc thc bng h iu hnh th khng cn thm ch xc thc no na truy cp SQL Server. Ch xc thc hn hp: Vi ch xc thc hn hp ngi dng c th truy cp vo SQL Server bng xc thc thc Windows hoc bng xc thc SQL Server. Khi ch xc thc kt hp c dng, kt ni c to t h thng khng bo mt, SQL Server xc thc ng nhp bng cch kim tra ti khon ng nhp c c thit lp truy cp hay khng. SQL Server thc hin xc thc ti khon ny bng cch so snh tn ti khon v mt khu do ngi dng cung cp thc hin kt ni vi thng tin ti khon c lu trong CSDL. Nu ti khon ng nhp cha c thit lp hoc ngi dng nhp sai th SQL Server t chi kt ni. Thit lp ch xc thc: * i vi SQL Server 2000: + Trong ca s Enterprise Manager, Right click ln tn server qun l CSDL m mun thit lp ch xc thc v chn Properties. Xut hin ca s Properties nh hnh 3.58. Chn tab Security.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

111

+ Vng Security ta chn ch xc thc: SQL Server and Windows hoc Windows Only. V cc mc d xt hnh v ng nhp, ty thuc vo yu cu o mt. C 4 mc cho sn l: o None: Khng thc hin d xt hnh vi, o Success: Ghi nhn tt c cc ng nhp thnh cng, o Failure: Ghi nhn nhng ng nhp khng thnh cng, o All: ghi nhn tt c cc ln ng nhp. + Trong vng Startup service account: Ch ra ti khon Windows c dng khi SQL Server khi ng. + System account: cc ti khon h thng cc b c xy dng sn. + This account: Ch ra mt ti khon c th.

Hnh 3.58. Ca s Properties


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

112

* i vi SQL Server 2005: + Trong ca s SQL Server Management Studio, right click vo th hin ca SQL Server mun thit lp ch xc thc v chn Properties xut hin ca s Server Properties (Hnh 3.59), chn trang Security.

Hnh 3.59. Ca s Server Properties + Mc Server Authentication: Chn ch xc thc Window (Windows Authentication mode) hoc ch xc thc hn hp (SQL Server and Windows Authentication mode) + Login Auditing: Kiu ghi nhn thng tin login (None, Failed logins only, Successful login only, )

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

113

b) Ngi dng v ng nhp Ti khon dng kt ni ti SQL Server c gi l ti khon ng nhp SQL Server. Cng vi ti khon ng nhp SQL Server, mi CSDL c mt ti khon ngi dng o c gn vi n. Nhng ti khon o ny cung cp mt b danh ti ti khon ng nhp SQL Server c gi l ti khon ngi dng CSDL. * To ti khon ng nhp SQL Server: Dng Enterprise manager: + Trong ca s Enterprise Manager, m rng server mun to ti khon ng nhp v m rng mc Security. Right click ln Logins v chn New Login xut hin ca s SQL Server Login Properties (hnh 3.60).

Hnh 3.60. Ca s New Login + Trn tab General:

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

114

+ Name: Nhp tn ti khon ng nhp. nu chn ch xc thc bng Window th tn ti khon ng nhp phi l ti khon tn ti trong Windows. + Authentication: Chn ch xc thc ca Windows l Windows Authentication hay ch xc hn hp SQL Server Authentication. + Default: Chn CSDL v ngn ng mc nh s c dng. + Tab Server Roles: y ta chn nhm quyn server cho ng nhp mi bng cch chn cc nhm quyn trong danh sch. Click vo nt Properties xem v sa i nhm quyn chn. Nu l ti khon ng nhp thng th khng cn cp quyn server. + Tab Database Access: Cho php chn CSDL m ngi dng c php truy cp. Dng SQL Server Management Studio: + Trong ca s SQL Server Management Studio, m rng th hin server mun to ti khon ng nhp v m rng mc Security. Right click ln Logins v chn New Login xut hin ca s Login New (hnh 3.61). + Trang General c cc la chn: Login Name: Nhp tn ti khon ng nhp. Nu chn ch xc thc bng Window th tn ti khon ng nhp phi l ti khon tn ti trong Windows. Default database: Chn CSDL mc nh c s dng. Default language: Chn ngn ng mc nh.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

115

Hnh 3.61. Ca s Login - New + Trang Server Roles c cc la chn: Chn nhm quyn server cho ng nhp mi bng cch chn cc nhm quyn trong danh sch (Hnh 3.62). + Trang User Mapping (Hnh 3.63): Cho php chn CSDL m ngi dng c php truy cp.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

116

Hnh 3.62. Ca s Login - New

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

117

Hnh 3.63. Ca s Login - New Dng T-SQL: Ta c th to ti khon ng nhp bng th tc sp_addlogin hoc sp_grandlogin. + Th tc sp_addlogin ch c th thm ngi dng c xc thc bng SQL Server. + Th tc sp_grandlogin c th thm ngi dng c xc thc bng Windows. V d 3.11. To ti khon ng nhp Huongct vi Password l abcd v CSDL mc nh l QLDiemSV
EXEC sp_addlogin 'Huongct1','abcd','QLDiemSV'

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

118

V d 3.12. To ti khon ng nhp Huongct vi ch xc thc Windows.


EXEC sp_grantlogin 'THUHUONG\Huongct'

Ngoi ra, i vi SQL Server 2005 ta c th s dng c php TSQL sau: + To Login CREATE LOGIN login_name { WITH PASSWORD = 'password' [,<option_list>[ ,... ]] | FROM WINDOWS [ WITH <windows_options> [ ,... ]]} <option_list> ::= DEFAULT_DATABASE = database | DEFAULT_LANGUAGE = language | CHECK_EXPIRATION = { ON | OFF} | CHECK_POLICY = { ON | OFF} [ CREDENTIAL = credential_name ] <windows_options> ::= DEFAULT_DATABASE = database | DEFAULT_LANGUAGE = language + Sa Login
ALTER LOGIN login_name { <status_option> | WITH <set_option> [ ,... ] } <status_option> ::= ENABLE | DISABLE <set_option> ::= PASSWORD = 'password' [ OLD_PASSWORD = 'oldpassword' ] | DEFAULT_DATABASE = database | DEFAULT_LANGUAGE = language | NAME = login_name | CHECK_POLICY = { ON | OFF } | CHECK_EXPIRATION = { ON | OFF }

+ Xa Login
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

119

DROP LOGIN login_name

V d 3.13. To cc login To Login HUONGCT dng ch xc thc SQL


USE master CREATE LOGIN HUONGCT WITH PASSWORD = '123456'; GO -

To Login [HP520-9B01514BF\Hp520] t domain account Windows.


CREATE LOGIN [HP520-9B01514BF\Hp520] FROM WINDOWS; GO

Sa Login HUONGCT
USE master ALTER LOGIN HUONGCT WITH PASSWORD = '12102006',DEFAULT_DATABASE = QLDiemSV;

Xa Login HUONGCT
USE master DROP LOGIN HUONGCT

Dng Wizard trong SQL Server 2000: Vo Tools\Wizard xut hin ca s hnh 3.5. Chn mc Database v chn Create Login Wizard. Sau thc hin theo s ch dn ca trnh Wizard. * To ngi dng SQL Server: to ngi dng SQL Server, trc ht ta phi to ng nhp SQL Server cho ngi dng v tn ngi dng tham chiu n tn ng nhp. Dng Enterprise manager: + Trong ca s Enterprise Manager, m rng mc Database. Right click CSDL mun to ngi dng v chn New\Database User xut hin ca s New User (hnh 3.64).

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

120

Hnh 3.64. Ca s New User + Nhp tn ng nhp hp l trong danh sch cc tn ng nhp ca hp combo Login Name v nhp tn ngi dng mi vo hp User Name (Mc nh SQL Server t in tn User Name trng tn Login Name, ta c th thay i tn ny) + Chn nhm quyn CSDL m ngi dng mi ny l thnh vin, sau chn OK. Dng SQL Server Management Studio: + Trong ca s SQL Server Management Studio, m rng th hin server v mc Database. M rng mc Security ca c s d liu mun to ngi dng, Right click ln Users v chn New User xut hin ca s Database User New (hnh 3.65). + Trang General c cc la chn:

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

121

User name: Nhp tn ngi dng Login name: Nhp tn hoc chn Login m ngi dng ny nh x n.

Hnh 3.65. Ca s Database User - New Dng T-SQL: Ta c th to ngi dng mi bng th tc sp_adduser. i vi SQL Server 2005 ta c th dng c php sau: + To User
CREATE USER user_name { { FOR | FROM } LOGIN login_name | WITHOUT LOGIN } [ WITH DEFAULT_SCHEMA = schema_name ]

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

122

+ Sa User
ALTER USER user_name WITH <set_item> [ ,...n ] <set_item> ::= NAME = new_user_name | DEFAULT_SCHEMA = schema_name

+ Xa User
DROP USER user_name

V d 3.14. To cc ngi dng mi l Huong vi tn ng nhp Huongct trn CSDL QLDiemSV


USE QLDiemSV Go sp_adduser 'Huongct,Huong'

V d 3.15. To cc ngi dng mi trng vi tn ng nhp Huongct trn CSDL QLDiemSV s dng xc thc ca Windows
USE QLDiemSV Go sp_adduser 'THUHUONG\Huongct'

V d 3.16. To cc User
CREATE USER Huongct WITHOUT LOGIN CREATE USER ChuHuong FOR LOGIN CHUHUONG

3.3.1.2. Qun l nhm quyn CSDL Cc nhm quyn CSDL c thit k cho php cc nhm nhng ngi dng nhn cc quyn CSDL ging nhau m khng cn phi cp quyn mt cch ring bit cho tng ngi dng. a) Cc nhm quyn Server c nh Mt s nhm quyn cp server c nh ngha trc ti thi im ci t SQL Server. Nhng nhm quyn c nh ny c dng cp quyn cho ngi qun tr CSDL. Cc nhm quyn server c nh c lit k trong danh sch sau: + bulkadmin: C th thc thi lnh BULK INSERT thm lng ln d liu vo bng.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

123

+ dbcreator: C th to v sa i CSDL. + diskadmin: C th qun l cc tp tin trn a. + processadmin: C th qun l cc qu trnh ca SQL Server. + securityadmin: C th qun l ng nhp v to cc quyn CSDL. + serveradmin: C th thit lp bt k ty chn server no v c th ng CSDL. + setupadmin: C th qun l cc server lin kt v c th ng CSDL. + sysadmin: C th thc hin bt k hot ng server no. Thm ngi dng vo cc nhm quyn server c nh. Dng Enterprise Manager + Trong ca s Enterprise Manager, m rng server v m rng mc Security. Sau chn server roles v right click ln nhm quyn server mun thm ngi dng, chng hn chn System Administrators xut hin ca s hnh 3.66.

Hnh 3.66. Ca s Server Role Propeties


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

124

+ Click nt Add thm ngi dng vo trong nhm. Dng SQL Server Management Studio + Trong ca s SQL Server Management Studio, m rng mc Security cp Server. Sau chn Server roles v right click ln ln nhm quyn server mun thm ngi dng, chng hn chn System Administrators xut hin ca s hnh 3.67.

Hnh 3.67. Ca s Server Role Propeties + Click vo nt Add thm ngi dng vo nhm. Hp thoi Select Login xut hin (Hnh 3.68). + Click vo nt Browse chn ng nhp ta mun thm vo nhm. Xut hin hp thoi Browse for Objects (Hnh 3.69)
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

125

Hnh 3.68. Ca s Select Login

Hnh 3.69. Ca s Browse for Objects + Chn cc Login v click OK ng ca s Browse for Objects. + Click OK ng ca s Select Logins. + Click OK ng ca s Server Role Propeties thm ngi dng chn vo nhm.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

126

b) To v sa i nhm quyn Dng Enterprise manager: + Trong ca s Enterprise Manager, m rng mc Database. Right click CSDL mun to nhm ngi dng v chn New\Database Role xut hin ca s (hnh 3.70). + Trong ca s ny ta nhp tn m t nhm v Add cc ti khon ngi dng thuc nhm bng cch click vo nt Add v chn cc ngi dng trong danh sch. Sau click nt OK to nhm. + Tr v Enterprise Manage, chn mc Roles ta s thy nhm quyn mi va to danh mc bn phi. + Ta gn quyn cho nhm bng cch right click ln nhm quyn v chn Propeties. Xut hin ca s Database Role Propeties v chn Permissions xut hin ca s hnh 3.71.

Hnh 3.70. Ca s New Role

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

127

Hnh 3.71. Ca s Database Role Propeties + Ta thc hin gn cc quyn cho cc nhm quyn ny trn cc i tng ca CSDL v click OK. Dng SQL Server Management Studio: SQL Server 2005 cung cp hai loi nhm quyn do ngi dng nh ngha + Database Roles: y l nhm quyn chun, dng cho cc tc v gn quyn ti c s d liu. + Application Roles: Dng cho cc quyn lin quan n ng dng. Xy dng nhm quyn Database Role ta tin hnh thc hin theo cc bc sau: + Trong SQL Server Management Studio, m rng mc Security cp CSDL ca CSDL ta mun to nhm quyn. + M rng mc Roles, right click ln mc Database Roles v chn New Database Role xut hin ca s Database Role New (Hnh 3.72)

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

128

Hnh 3.72. Ca s Database Role - New Dng T-SQL: + Ta thc hin thng qua 2 bc. 1. To nhm quyn: Ta c th to nhm quyn bng th tc sp_addrole. i SQL Server 2005 ta c th dng c php sau:
CREATE ROLE role_name [AUTHORIZATION owner_name ]

Role name: Nhp tn nhm Owner: Chn danh sch cc ngi dng. Members of this role: Click vo nt Add thm cc ngi dng vo nhm.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

129

Trong : role_name: L tn ca nhm s c to. AUTHORIZATION owner_name : L ngi dng CSDL hoc cc nhm m s hu nhm mi ny. Nu khng c ngi dng no ch nh th nhm s c s hu bi ngi dng thc hin cu lnh CREATE ROLE ny.

V d 3.21. To nhm quyn xem_dl trn CSDL QLDiemSV.


Use QLDiemSV Go Sp_addrole xem_dl

2. Thm quyn vo nhm: Ta c th thm quyn vo nhm bng vic s dng lnh GRANT v thu hi quyn ca nhm s dng lnh REVOKE. V d 3.22. Ta thm quyn SELECT bng HOSOSV vo nhm xem_dl trn CSDL QLDiemSV.
Use QLDiemSV Go GRANT SELECT ON HOSOSV TO xem_dl

3. Thm ngi dng vo nhm quyn: thm ngi dng vo nhm quyn ta s dng th tc sp_addrolemember V d 3.23. Thm ngi dng Guest vo nhm quyn xem_dl trn CSDL QLDiemSV.
Use QLDiemSV Go Sp_addrolemember xem_dl,Guest Go

3.3.1.3. Qun l quyn CSDL Xc thc ngi dng l qu trnh m bo ch c nhng ngi dng hp l mi c php lm vic vi c s d liu. Sau khi ngi dng truy cp c vo CSDL th h c cc quyn c th vi cc i tng trong CSDL.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

130

Cc quyn trn cc i tng l:


+

i tng database: BACKUP DATABASE, BACKUP LOG, CREATE DATABASE, CREATE DEFAULT, CREATE FUNCTION, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, v CREATE VIEW. i tng scalar function: EXECUTE v REFERENCES. i tng table-valued function: DELETE, REFERENCES, SELECT, v UPDATE. INSERT,

+ +

i tng stored procedure: DELETE, EXECUTE, INSERT, SELECT, v UPDATE. i tng table: DELETE, INSERT, REFERENCES, SELECT, v UPDATE. i tng view: DELETE, INSERT, REFERENCES, SELECT, and UPDATE.

Cp quyn trn cc i tng CSDL ta tin hnh thc hin nh sau: Dng Enterprise manager cp quyn trn cc i tng: C hai cch qun l quyn trn cc i tng. Cch 1: Gn quyn cho tt c cc i tng cho mt ngi dng hoc mt nhm ngi dng. + Trong ca s Enterprise Manager, m rng mc Database. Chn CSDL mun cp quyn v m rng mc Users. Sau right click ln tn ngi dng mun cp quyn v chn Properties, xut hin ca s nh hnh 3.73. + Click vo nt Permissionss hin th ca s Database Users Properties nh hnh 3.74. Ta gn cc quyn cho ngi dng ny trn cc i tng bng cch chn hp kim tng ng. Cc ty chn List all Objects dng lit k tt c cc i tng cn chn List only objects with permissions for this user th ch lit k cc i tng m ngi dng ny c quyn truy cp.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

131

Hnh 3.73. Ca s Database Users Properties

H Hnh 3.74. Ca s Database Users Properties

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

132

Cch 2: Gn cc quyn trn mt i tng cho tt c cc ngi dng hoc cc nhm ngi dng. + Trong ca s Enterprise Manager, m rng mc Database. Sau right click ln CSDL mun cp quyn, v d QLDiemSV v chn Properties, xut hin ca s nh hnh 3.75. Chn tab Permissions. + Thc hin cp quyn thc thi cho cc ngi dng bng cch tch vo tng ng vi cc quyn .

+ + + + + + + + Hnh 3.75. Ca s QLDiemSV Properties Dng SQL Server Management Studio cp quyn trn cc i tng: C hai cch qun l quyn trn cc i tng. Cch 1: Gn quyn cho tt c cc i tng cho mt ngi dng hoc mt nhm ngi dng.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

133

+ Trong ca s Object Explorer ca SQL Server Management Studio, m rng mc Database. Chn CSDL mun cp quyn v m rng mc Users hoc Roles\Database Roles. + Right click ln ngi dng hoc nhm ngi dng mun v chn Properties. Hp thoi Properties xut hin chn trang Securables (Hnh 3.76)

Hnh 3.76. Ca s Database User + Click nt Add thm cc i tng mun bo mt. Hp thoi Add Objects xut hin (Hnh 3.77), ta ch cc i tng mun bo mt. Specific objects: Ch nh cc i tng c th.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

134

All objects of the types: Tt c cc i tng ca cc kiu c th. All objects belong to schema: Cc i tng thuc gin .

Hnh 3.77. Ca s Add Objects + Nu chn ty chn Specific objects, click OK hp thoi Select Object xut hin (Hnh 3.78).

Hnh 3.78. Ca s Select Objects + Click vo nt Object Types, hp thoi Select Object Types xut hin nh hnh 3.79. Ta chn cc kiu i tng m mun bo mt cho ngi dng v click OK.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

135

Hnh 3.79. Ca s Select Object Type + Click vo nt Browse trn hp thoi Select Objects (Hnh 3.78) xut hin ca s Browse for Objects hnh 3.80. Ta chn cc i tng m mun bo mt cho ngi dng v click OK. + Click OK trn ca s Select Objects quay tr li trang Securable ca hp thoi Database User nh hnh 3.81. Ta chn tng i tng v cp quyn cho ngi dng ny.

Hnh 3.80. Ca s Browse for Objects

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

136

Hnh 3.81. Ca s Database User Dng T-SQL cp quyn: Ta dng lnh cc lnh + GRANT: cp quyn cho ngi dng; + DENY: dng ngn cn quyn ca ngi dng no . Ngn cn cc ngi dng t vic k tha cc quyn trong nhm. + REVOKE: thu hi li quyn cp. C c php nh sau: GRANT { | [ [ ALL } permission [( column [ ,...n ] ) ] [ ,...n ] ON securable ] TO principal [ ,...n ] WITH GRANT OPTION ]

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

137

DENY { ALL } | permission [( column [ ,...n ] ) ] [ ,...n ] [ ON securable ] TO principal [ ,...n ] [ CASCADE] REVOKE [ GRANT OPTION FOR ] { [ ALL ] |permission[( column [ ,...n ] ) ] [ ,...n ] } [ ON securable ] { TO | FROM } principal [ ,...n ] [ CASCADE] Trong : + ALL: Cp tt c cc quyn ; + permission: Tn cc quyn c th c cp; + column: Tn cc ct ca bng m cc quyn c c cp; + securable: Ch nh i tng ang cp quyn trn . + Principal: Ch nh ngi c cp quyn. + WITH GRANT OPTION: Ch nh ngi c cp quyn c th cp quyn ny cho ngi khc.
+ CASCADE: Ch nh ngn cn (i vi DENY) hoc thu hi (i

vi REVOKE) theo dy truyn i vi cc ngi dng c cp quyn vi t kha WITH GRANT OPTION. V d 3.15. Trao cc quyn INSERT, SELECT, UPDATE cho Huongct trn CSDL QLDiemSV.
Use QLDiemSV Go GRANT INSERT,SELECT, UPDATE ON HOSOSV TO Huongct

V d 3.16. Trao tt c cc quyn cho Huongct trn CSDL QLDiemSV.


Use QLDiemSV Go

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL GRANT ALL ON LOP TO Huongct

138

V d 3.17. Ly cc quyn INSERT, UPDATE ca Huongct trn CSDL QLDiemSV.


Use QLDiemSV Go REVOKE INSERT,UPDATE ON HOSOSV TO Huongct

V d 3.18. Ly tt c cc quyn ca Huongct trn bng LOP ca CSDL QLDiemSV.


Use QLDiemSV Go REVOKE ALL ON LOP TO Huongct

V d 3.19. Cp cc quyn CREATE TABLE, CREATE VIEW cho Huongct trn CSDL QLDiemSV.
Use QLDiemSV Go GRANT CREATE TABLE, CREATE VIEW TO Huongct

V d 3.20. Thu hi tt c cc quyn ca Huongct trn CSDL QLDiemSV.


Use QLDiemSV Go REVOKE ALL TO Huongct

3.3.2. Sao lu - phc hi CSDL 3.3.2.1.Sao lu CSDL Sao lu l hot ng d liu c sao chp t CSDL v lu mt ni khc. C nhiu phng php sao lu CSDL khc nhau, l: Sao lu y (Full Database): L sao lu ton b CSDL, tt c cc nhm tp tin v tp tin CSDL l mt phn ca CSDL u

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

139

c sao lu. y l k thut ph bin dng cho cc CSDL c kch thc va v nh. Sao lu nhng thay i (Differential Database): Cho php ch sao lu nhng d liu thay i k t ln sao lu gn nht. K thut ny nhanh hn v t tn khng gian lu tr hn so vi sao lu y . Nhng dng phng php ny kh khn hn v tn nhiu thi gian gian hn khi phc d liu. Sao lu tp tin log giao dch (Transaction Log): Cho php sao lu transaction log, sao lu ny rt quan trng cho phc hi CSDL. Sao lu nhm tp tin (Full File Group): bao gm sao lu tt c cc tp tin d liu kt hp vi tp tin n trong CSDL. Dng phng php ny sao lu cc nhm tp tin ring bit ty thuc vo cch h thng c cu hnh Sao lu tp tin d liu (Full File): Cho php sao lu mt tp tin n trong nhm tp tin. Phng php ny kt hp vi kh nng ca SQL Server khi phc mt tp tin d liu n ring bit. Thc hin sao lu d liu: Ta c th thc hin bng cc phng php nh dng: i vi SQL Server 2000: Enterprise manager, T-SQL, Create Database Backup Wizard. i vi SQL Server 2005: Phng php s dng SQL Server Management Studio, T-SQL Physical and Logical Devices SQL Server Database Engine nhn dng cc thit b back up (backup devices) hoc l tn thit b vt l (physical device) hoc tn logic (logical device) : Thit b sao lu vt l l tn c s dng bi h iu hnh cho vic nhn dng thit b back up. V d: C:\Backups\Accounting\Full.bak.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

140

Thit b sao lu logic l b danh do ngi dng nh ngha, c s dng nhn dng mt thit b sao lu vt l. Tn thit b logic c lu tr thng trc trn cc bng h thng trong SQL Server. Tin li ca vic s dng thit b sao lu logic l tn ca n n gin hn so vi tn thit b vt l. V d, ta s dng tn logic l Accounting_Backup nhng tn vt l c th l E:\Backups\Accounting\Full.bak.

Hot ng sao lu c th hng ti thit b vt l hoc thit b logic. Thit b vt l l a cng, bng t,.v.v cn thit b logic ch tn ti trong SQL Server v ch c dng cho SQL Server thc hin sao lu. sao lu ti thit b logic, ta phi to thit b trc. Dng Enterprise manager: To thit b sao lu logic: + Trong ca s Enterprise Manager, m rng server mun thc hin sao lu v m rng mc Management. + Right click ln danh mc Backup v chn New Backup Device xut hin ca s Backup Device Propeties (Hnh 3.82). Ta nhp tn cho thit b sao lu vo hp Name v ng dn lu file vo hp thoi File Name. Sau click OK lu li.

Hnh 3.82. Ca s Backup Device Propeties


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

141

Thc hin sao lu: + Trong ca s Enterprise Manager, m rng server mun thc hin sao lu v m rng mc Management. + Right click ln danh mc Backup v chn New Backup a Database xut hin ca s SQL Server Backup (Hnh 3.83).

Hnh 3.83. Ca s SQL Server Backup + Trong danh sch Database chn CSDL mun thc hin sao lu, chng hn chn QLDiemSV. Tn sao lu c in t ng vo hp Name, ta c th thay i tn ny. Nhp m t vo hp Description. + Trong vng BACKUP ch ra kiu sao lu. C cc ty chn c sn nh l:
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

142

Database Complete: Thc hin sao lu y CSDL. Database Differential: Thc hin sao lu phn thay i. Transaction log: Thc hin sao lu tp tin log giao dch. File and filegroup: Thc hin sao lu tp tin v nhm tp tin. + Trong vng Destination: Click vo nt Add xut hin ca s Select Backup Destination hnh 3.84. o File Name: Chn vo ty chn ny thc hin sao lu thnh mt tp tin lu trc tip xung h iu hnh (dng thit b vt l) o Backup device: Chn thit b sao lu logic. Chn Thietbi_Saoluu va to mc trn v chn OK.

Hnh 3.84. Ca s Select Backup Destination + Trong vng Overwrite: C 2 ty chn Append to media: Ghi ni tip vo thit b Overwrite existing media: ghi ln thit b ang tn ti. + Trong vng Shedule: Dng khi mun thit lp biu sao lu t ng.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

143

+ Click OK thc hin sao lu. Dng SQL Server Management Studio: To thit b sao lu logic: + Trong ca s Object Explorer, click vo tn server m rng cy server. + M rng mc Server Objects, v right-click Backup Devices v chn New Backup Device. Xut hin hp thoi Backup Device (Hnh 3.85). Trong hp thoi mc: Device name: Nhp tn thit b logic. Destination, click File v ch nh ng dn y ca file.

Hnh 3.85. Ca s Backup Device


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

144

Thc hin sao lu: + Trong ca s Object Explorer, click vo tn server m rng cy server. + M rng mc Databases, v right-click ln c s d liu mun to file Backup v chn Tasks\Back Up. Xut hin hp thoi Back Up Database (Hnh 3.86).

Hnh 3.86. Ca s Back Up Database + Trong hp thoi ta thc hin cc la chn: Vng Source: Database: Chn Database mun to file Back Up; Backup type: Chn kiu Back Up.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

145

Vng Backup set: Thit lp tn, m t, file BackUp. Vng Destination: Mc Backup to chn Disk v click vo nt Add chn thit b sao lu. Xut hin ca s Select Backup Destination (Hnh 3.87) ta s chn kiu thit b sao lu vt l (chn File name) hoc logic (Backup device) v click OK.

Hnh 3.87. Ca s Select Backup Destination + Ta click vo nt OK trn ca s Back Up Database thc hin qu trinhd sao lu. 3.3.2.2. Phc hi d liu Phc hi d liu c th coi l mt qu trnh ngc vi qu trnh sao lu, d liu sao chp c sao chp tr li CSDL. Loi sao lu d liu s nh hng n cch khi phc d liu. Ta thc hin cc bc sau khi phc d liu. Dng Enterprise manager: Trong ca s Enterprise Manager, right click ln mc Database. Chn All Task/Restore Database. Khi xut hin hp thoi Restore Database hnh 3.88.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

146

Chn tab General, mc Restore As Database cho php ch ra CSDL s c phc hi t d liu sao lu. V d ta chn CSDL QLDiemSV th vic khi phc d liu sao lu s thay th ton b d liu hin thi trong QLDiemSV. Khi ta phi chn hp check box Force Restore Over Existing Database trong tab Options. SQL Server khng i hi phi khi phc CSDL trc tip m cho php ta khi phc d liu vi mt ci tn khc. V d, ngi dng xa nhm bng d liu. Nh vy, nu ta khi phc ton b d liu th d liu c s thay th ton b d liu ang c trn cc bng khc. Thay vo ta khi phc vi mt ci tn khc sau trch bng b xa v thm vo CSDL b mt. V d ta thay vi tn QLDiemSV_Restore.

Hnh 3.88. Ca s Restore Database.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

147

Trong vng Restore chn From Device. Trong vng Paramaters chn Restore backup set v chn Database complete. Click vo nt Select Device xut hin hp thoi Choose Restore Device nh hnh 3.89.

Hnh 3.89. Ca s Choose Restore Device. V chn nt Add xut hin hp thoi Choose Restore Destination (Hnh 3.90).

Hnh 3.90. Ca s Choose Restore Destination.


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

148

Trong c hai la chn: + File name: Chn tp tin sao lu trn thit b vt l. + Backup Device: Chn tn thit b logic. Sau chn OK tr v ca s hnh 3.89. Trong ca s 3.89 click OK tr v ca s 3.88. Chn tab Options: + Force Restore Over Existing Database: Chn nu ta thc hin khi phc trc tip CSDL vi d liu c s ln d liu mi. + Mc Move to physical file name: Ta c th sa i li thnh tn khc vi tn tp tin ban u. V d tp tin QLDiemSV_Restore.mdf chuyn thnh QLDiemSV_Restore_Data.mdf Click OK bt u thc hin phc hi d liu. Dng SQL Server Management Studio: Cc m hnh khi phc d liu: + Full Recovery Model: y l m hnh cho php phc hi d liu vi t ri ro nht. Nu mt database trong m hnh ny th tt c cc hot ng khng ch insert, update, delete m k c insert bng Bulk Insert, hay bcp u c log vo transaction log file. Khi c s c th ta c th phc hi li d liu ngc tr li ti mt thi im trong qu kh. Khi data file b h nu ta c th backup c transaction log file th ta c th phc hi database n thi im transaction gn nht c commited. + Bulk-Logged Recovery Model: m hnh ny ny cc hot ng mang tnh hng lot nh Bulk Insert, bcp, Create Index, WriteText, UpdateText ch c log minimum vo transaction log file cho bit l cc hot ng ny c din ra m khng log ton b chi tit nh trong Full Recovery Mode. Cc hot ng khc nh Insert, Update, Delete vn c log y dng cho vic phc hi sau ny.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

149

+ Simple Recovery Model: m hnh ny th Transaction Log File c truncate thng xuyn. Vi mo hnh ny bn ch c th phc hi ti thi im backup gn nht m khng th phc hi ti mt thi im trong qu kh. thay i m hnh Recovery, ta tin hnh thc hin nh sau: + Trong ca s Object Explorer, click vo tn server m rng cy server. + M rng mc Databases, v right-click ln c s d liu mun thay i m hnh Recovery v chn Properties. Xut hin hp thoi Database Properties, chn trang Options (Hnh 3.91). + Mc Recovery model: Ta chn m hnh khi phc d liu.

Hnh 3.91. Ca s Database Properties

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

150

Phc hi d liu: o Trong ca s Object Explorer, click vo tn server m rng cy server. o Right click ln mc Databases, v chn Restore Database xut hin ca s Restore Database (Hnh 3.92). C cc la chn.

Hnh 3.92. Ca s Restore Database + To database: in tn Database s c phc hi. Tn ny c th l mt tn Database mi hoc chn trong danh sch cc Database c trong Server.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

151

+ To a point in time: Restore database n thi im sn c backup gn y nht hoc n mt thi im c ch nh. + From database: Chn database restore t danh sch. Danh sch ny ch cha cc database c backed up theo nht k ca msdb backup. + From device: Chn ngun t tp cc file backup. Click vo nt browse xut hin ca s Specify Backup (Hnh 3.93). Tong hp thoi ny ta chn kiu thit b (Backup media) l thit b vt l hay thit b logic. Click nt Add ly cc file Backup dng phc hi d liu. o Trong ca s Restore Database, sau khi thit lp cc tham s click OK thc hin qu trnh phc hi d liu.

Hnh 3.93. Ca s Restore Database

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

152

Chng 4. LP TRNH TRN SQL SERVER 4.1. Gii thiu ngn ng T-SQL 4.1.1. Khi nim Transaction SQL (T-SQL) l ngn ng pht trin nng cao ca ngn ng SQL chun. N l ngn ng dng giao tip gia ng dng v SQL Server. T-SQL cc kh nng ca ngn ng nh ngha d liu - DDL v ngn ng thao tc d liu DML ca SQL chun cng vi mt s hm m rng, cc store procedure h thng v cu trc lp trnh (nh IF, WHILE,) cho php lp trnh trn SQL Server c linh ng hn. Trong cc chng trc ta gii thiu ngn ng SQL chun v lm quen vi cc cu lnh T-SQL dng nh ngha d liu, thao tc d liu nh: To CSDL, to bng, to View, to Index, chn d liu,.v.v Trong chng ny ta s tm hiu thm v T-SQL. 4.1.2. Pht biu truy vn d liu nng cao a) Mnh TOP Mnh TOP ch nh tp hp cc dng u tin c tr v trong truy vn. Tp hp cc dng c th l mt con s hoc theo t ln phn trm (PERCENT) cc dng d liu. Mnh TOP c s dng trong cc khi cu lnh Select, Insert, Update v Delete. C php:
[ ] TOP (expression) [PERCENT] [ WITH TIES ]

Trong : expression: L biu thc tr v gi tr kiu s. PERCENT: Ch nh s dng tr v l expression phn trm

trong tp kt qu.
WITH TIES: TOP ...WITH TIES ch c ch nh trn khi

cu lnh SELECT v c mnh ORDER BY. Ch nh thm cc dng t tp kt qu c s c cng gi tr vi cc ct


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

153

trong mnh ORDER BY xut hin nh l dng cui cng ca TOP n (PERCENT). V d 4.1. S dng mnh TOP - Trong cu lnh Insert
INSERT TOP (2) INTO LOP SELECT * FROM DMLOP ORDER BY Khoa

- Trong cu lnh Select


INSERT INTO LOP SELECT TOP (2) WITH TIES * FROM DMLOP ORDER BY Khoa

b) iu kin kt ni - JOIN Trong khi cu lnh SELECT, mnh FROM ta c th s dng pht biu JOIN kt ni cc bng c quan h vi nhau. Mnh kt ni Join c phn loi nh sau:

Inner joins (ton t thng dng kt ni thng l cc ton t so snh = hoc <>). Inner joins s dng mt ton t so snh so khp cc dng t hai bng da trn cc gi tr ca cc ct so khp ca mi bng. Kt qu tr v ca Inner Join l cc dng tha mn iu kin so khp.

Outer joins. Outer joins c th l left, right, hoc full outer join.
+

LEFT JOIN hoc LEFT OUTER JOIN : Kt qu ca left outer join khng ch bao gm cc dng tha mn iu kin so khp gia hai bng m cn gm tt c cc dng ca bng bn tri trong mnh LEFT OUTER. Khi mt dng bng bn tri khng c dng no ca bng bn phi so khp ng th cc gi tr NULL c tr v cho tt c cc ct bng bn phi.

RIGHT JOIN or RIGHT OUTER JOIN: Right outer join l nghch o ca left outer join. Tt c cc dng ca bng bn phi c tr v. Cc gi tr Null cho bng bn tri khi

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

154

bt c mt dng no bn phi khng c mt dng no bng bn tri so khp ng.


+

FULL JOIN or FULL OUTER JOIN: full outer join tr v tt c cc dng trong c hai bng bn tri v phi. Bt k mt dng khng c dng so khp ng ca bng cn li th bng cn li nhn cc gi tr NULL. Khi c s so khp ng gia cc bng th tp kt qu s cha d d liu cc bng c s .

Cross joins: Tr v tt c cc dng ca bng bn tri v mi dng bn tri s kt hp vi tt c cc dng ca bng bn phi. Cross joins cn c gi l tch cc (Cartesian products). V d 4.2. S dng Join Inner Joins:
SELECT MONHOC.MaMH, MONHOC.TenMH, MONHOC.SDVHT, DIEM.MaSV, DIEM.DiemL1 FROM DIEM INNER JOIN MONHOC ON DIEM.MaMH = MONHOC.MaMH

Left Joins:

SELECT MONHOC.MaMH, MONHOC.TenMH, MONHOC.SDVHT, DIEM.MaSV, DIEM.DiemL1 FROM MONHOC LEFT JOIN DIEM ON MONHOC.MaMH= DIEM.MaMH

Right Joins:

SELECT MONHOC.MaMH, MONHOC.TenMH, MONHOC.SDVHT, DIEM.MaSV, DIEM.DiemL1 FROM DIEM Right JOIN MONHOC ON DIEM.MaMH= MONHOC.MaMH

Full Joins:

SELECT MONHOC.MaMH, MONHOC.TenMH, MONHOC.SDVHT, DIEM.MaSV, DIEM.DiemL1 FROM DIEM Full JOIN MONHOC ON DIEM.MaMH= MONHOC.MaMH

Cross Joins:

SELECT MONHOC.MaMH, MONHOC.TenMH, MONHOC.SDVHT, DIEM.MaSV, DIEM.DiemL1 FROM MONHOC CROSS JOIN DIEM

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

155

c) Truy vn Cross tab Trong mt s trng hp thng k, ta cn phi xoay bng kt qu, do c cc ct c biu din theo chiu ngang v cc dng c biu din theo chiu dc (c gi l truy vn cross tab). V d 4.3. V d ta c mt view tnh tng gi tr ca mt ha n View_Order (OrderID, OrderDate, Month, Year, Total). Ta cn thng k doanh thu theo tng thng ca cc nm.
SELECT Year, SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month SUM(CASE Month FROM View_Order GROUP BY Year WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN WHEN 1 THEN Total ELSE 0 END) AS Jan, 2 THEN Total ELSE 0 END) AS feb, 3 THEN Total ELSE 0 END) AS mar, 4 THEN Total ELSE 0 END) AS apr, 5 THEN Total ELSE 0 END) AS may, 6 THEN Total ELSE 0 END) AS jun, 7 THEN Total ELSE 0 END) AS jul, 8 THEN Total ELSE 0 END) AS aug, 9 THEN Total ELSE 0 END) AS sep, 10 THEN Total ELSE 0 END) AS oct, 11 THEN Total ELSE 0 END) AS nov, 12 THEN Total ELSE 0 END) AS dec

Kt qu:

S dng ton t PIVOT v UNPIVOT SQL Server 2005 a ra cc ton t n gin hn cho vic to truy vn cross tab, l ton t PIVOT v UNPIVOT trong mnh FROM ca khi cu lnh SELECT.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

156

+ Ton t PIVOT thc hin xoay mt biu thc gi tr bng (table valued expression) thnh mt bng khc bng vic a cc gi tr duy nht ca mt ct thnh cc ct v thc hin cc hm thng k trn cc ct cn li. + Ton t UNPIVOT thc hin qu trnh ngc li vi qu trnh thc hin ca ton t PIVOT, xoay cc ct ca biu thc bng thnh gi tr ca mt ct. C php: FROM { <table_source> } [ ,...n ] <table_source> ::= { <pivoted_table> | <unpivoted_table> [ ,...n ] } <pivoted_table> ::= table_source PIVOT <pivot_clause> table_alias <pivot_clause> ::= ( aggregate_function( value_column ) FOR pivot_column IN ( <column_list> ) ) <unpivoted_table> ::= table_source UNPIVOT <unpivot_clause> table_alias <unpivot_clause> ::= ( value_column FOR pivot_column IN ( <column_list> ) ) <column_list> ::= column_name [ , ... ] Trong :
+ table_source

PIVOT <pivot_clause> : Ch nh bng table_source c xoay da trn ct pivot_column. table_source l mt bng hoc biu thc bng. Output l mt
B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

Bi ging H qun tr CSDL

157

bng cha tt c cc ct ca table_source tr ct pivot_column v value_column. Cc ct ca table_source, tr pivot_column v value_column, c gi l cc ct phn nhm ca ton t pivot. + aggregate_function: L mt hm thng k ca h thng hoc do ngi dng nh ngha. Hm COUNT(*) khng c php s dng trong trng hp ny.
+ value_column: L ct gi tr ca ton t PIVOT. Khi s dng

vi ton t UNPIVOT, value_column khng c trng tn vi cc ct trong bng input table_source. + FOR pivot_column : Ch nh trc xoay ca ton t PIVOT. pivot_column l c kiu chuyn i c sang nvarchar(). KHng c l cc kiu image hoc rowversion. Khi UNPIVOT c s dng, pivot_column l tn ca ct output c thu hp li t table_source. Tn ct ny khng c trng vi mt tn no trong table_source. + IN ( column_list ) : Trong mnh PIVOT, danh sch cc gi tr trong pivot_column s tr thnh tn cc ct trong bng output. Danh sch ny khng c trng vi bt k tn ct no tn ti trong bng input table_source m ang c xoay. Trong mnh UNPIVOT, danh sch cc ct trong table_source s c thu hp li thnh mt ct pivot_column. + table_alias: L tn b danh ca bng output. pivot_table_alias phi c ch nh. + UNPIVOT < unpivot_clause > : Ch nh bng input c thu hp bng cc ct trong column_list tr thnh mt ct gi l pivot_column. * Hot ng ca ton t PIVOT: Ton t PIVOT thc hin theo tin trnh sau:

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

158

+ Thc hin GROUP BY da vo cc ct phn nhm trn bng input_table v kt qu l ng vi mi nhm cho mt dng out put trn bng kt qu.
+ Sinh cc gi tr ng vi cc ct trong danh sch column list cho

mi dng output bng vic thc thi nh sau: Nhm cc dng c sinh t vic GROUP BY bc trc da trn ct pivot_column. i vi mi ct output trong column_list, chn mt nhm con tha mn iu kin:
pivot_column=CONVERT(<data pivot_column>, 'output_column') type of

aggregate_function nh gi tr da tn ct value_column

trong nhm con ny v kt qu c tr v ca n tng ng l gi tr ca ct output_column. Nu nhm con l rng th SQL Server sinh gi tr NULL cho ct output_column . Nu hm thng k l COUNT th n sinh gi tr 0. V d 4.5. V d ta c mt view tnh tng gi tr ca mt ha n View_Order (OrderID, OrderDate, Month, Year, Total). Ta cn thng k doanh thu theo tng thng ca cc nm.
SELECT Year,[1]AS Jan,[2]AS feb, [3]AS mar,[4] AS apr,[5] AS may,[6] AS jun,[7] AS jul,[8] AS aug,[9] AS sep, [10]AS oct,[11] AS nov,[12] AS dec FROM (SELECT Year, Month,Total FROM View_Order) p PIVOT (Sum(Total) FOR Month IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]) )AS pvt

V d 4.6. S dng PIVOT


USE AdventureWorks GO SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5 FROM

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

159

(SELECT PurchaseOrderID, EmployeeID, VendorID FROM Purchasing.PurchaseOrderHeader) p PIVOT ( COUNT (PurchaseOrderID) FOR EmployeeID IN ( [164], [198], [223], [231], [233] ) ) AS pvt ORDER BY VendorID;

V d 4.7. S dng UNPIVOT


CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int, Emp3 int, Emp4 int, Emp5 int) GO INSERT INTO pvt VALUES (1,4,3,5,4,4) INSERT INTO pvt VALUES (2,4,1,5,5,5) INSERT INTO pvt VALUES (3,4,3,5,4,4) INSERT INTO pvt VALUES (4,4,2,5,5,4) INSERT INTO pvt VALUES (5,5,1,5,5,5) GO --Unpivot the table. SELECT VendorID, Employee, Orders FROM (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5 FROM pvt) p UNPIVOT (Orders FOR Employee IN (Emp1, Emp2, Emp3, Emp4, Emp5) )AS unpvt

d) UNION v UNION ALL Ton t UNION [ALL] dng hp kt qu ca hai hoc nhiu cu truy vn tng thch vi nhau. Hai cu truy vn tng thch l hai cu c cng cu trc, tc l c cng s ct v tp cc ct tng ng c cng kiu d liu hoc c cc kiu d liu tng thch nhau. C php ca cu lnh: select_statement UNION [ALL] select_statement Tn ca cc ct trong php ton UNION l tn cc ct trong tp kt qu ca khi cu lnh SELECT th nht trong UNION. Theo mc nh php ton UNION ch ly i din cho tp cc dng trng nhau. Nu ta s dng t kha ALL, th tt c cc dng c cho vo bng kt qu v cc dng trng nhau s khng loi b cc dng trng nhau.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

160

V d 4.8. S dng UNION SELECT * from LOP UNION ALL SELECT * from DMLOP 4.1.3. Lp trnh cu trc trong SQL Server a) Cc ton t - Ton t gn: K hiu l du = c dng gn gi tr cho mt bin hoc mt ct.
DECLARE @intValue int SELECT @intValue = 1 PRINT @intValue

hoc
DECLARE @intValue int SET @intValue = 1 PRINT @intValue

- Ton t s hc: l cc php ton cng (+), tr (-), nhn (*), chia (/) v chia modul (%) .
12+4=16 12-4=8 12*4=48 12/4=3 15%2=1

- Ton t so snh: l cc php ton so snh gia hai biu thc v tr v gi TRUE hoc FALSE. l cc php so snh: = (bng), <> (khc), > (ln hn), >= (ln hn hoc bng), < (nh hn), <= (nh hn hoc bng). - Ton t logic: Kim tra iu kin ng ca hai biu thc, chng thng c s dng cng vi cc ton t so snh tr v gi tr TRUE hoc FALSE. Cc ton t logic c cho trong bng 4.1 sau. Bng 4.1. Cc ton t logic Ton t ALL ngha So snh mt gi tr v hng vi mt tp cc gi tr ca mt ct c ly t mt cu truy vn con. ALL tr v gi tr TRUE nu tt c cc gi tr trong ct tr v gi tr TRUE ngc li tr v
B mn: Cc h thng thng tin

V d
5 > ALL (SELECT * FROM sales)

Bin son: Chu Th Hng

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

161

gi tr FALSE. AND Kt hp v so snh gia hai biu thc Boolean, nu c hai biu thc u TRUE th n tr v gi tr TRUE v ngc li n tr v gi tr FALSE. So snh mt gi tr v hng vi mt tp cc gi tr ca mt ct c ly t mt cu truy vn con. N s tr v gi tr TRUE nu c bt c gi tr no trong ct tr v gi tr TRUE. Nu khng c mt gi tr no tr v gi tr TRUE th n tr v gi tr FALSE. ANY tng t nh ton t SOME.
5 > 7 AND 6 < 15

ANY

5 > ANY (SELECT qty FROM sales)

BETWEEN Kim tra gi tr c nm gia phm vi c ch nh hay khng. Tr v gi tr TRUE nu n nm trong khong gi tr v ngc li tr gi tr FALSE. EXISTS Kim tra xem c gi tr no tr v khi thc hin mt cu truy vn. Nu c cc gi tr tr v th ton t cho gi tr TRUE, ngc li tr v gi tr FALSE. Kim tra xem mt gi tr c tn ti trong mt tp cc gi tr hay khng. Nu gi tr m thuc tp gi tr th ton t tr v gi tr TRUE, ngc li tr v gi tr FALSE. Dng so khp cc gi tr vi mt mu theo t kha LIKE. N s tr v gi tr TRUE nu khp vi mu ngc li tr v gi tr FALSE. K t % i din cho mt dy k t bt k, _ i din cho mt k t bt k.

5 BETWEEN (3 AND 10)

EXISTS (SELECT * FROM test)

IN

5 IN (SELECT qty FROM sales)

LIKE

SELECT name WHERE name LIKE S%

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

162
NOT 5 > 2 5 > 2 OR 10 < 3

NOT OR

Dng ph nh mt biu thc Boolean. Kt hp v so snh gia hai biu thc Boolean, nu mt trong hai biu thc l TRUE th n tr v gi tr TRUE v ngc li n tr v gi tr FALSE. So snh mt gi tr v hng vi mt tp cc gi tr ca mt ct c ly t mt cu truy vn con. N s tr v gi tr TRUE nu c bt c gi tr no trong ct tr v gi tr TRUE. Nu khng c mt gi tr no tr v gi tr TRUE th n tr v gi tr FALSE. SOME tng t nh ton t ANY.

SOME

5 > SOME (SELECT * FROM sales)

- Ton t ghp chui (+): Dng ghp hai chui vi nhau thnh mt chui. Ton t ghp chui c dng vi cc kiu d liu char, varchar, nchar, nvarchar, text, v ntext.
SELECT 'This' + ' is a test.'

- Ton t bit: Thc hin thao tc vi cc bit-lavel vi cc kiu d liu Integer. Cc ton t c cho trong bng 4.2. Bng 4.2. Cc ton t Bitwise Ton t & ngha Thc hin AND gia cc bit tng ng gia hai biu din nh phn ca hai s integer. Thc hin OR gia cc bit tng ng gia hai biu din nh phn ca hai s integer. Thc hin XOR gia cc bit tng ng gia hai biu din nh phn ca hai s integer. (hai bit ging nhau tr v bit 0, khc nhau tr v bit 1) V d
7 & 51 = 3 ( 7=111, 51=110011, 3=11) 7 | 51 = 55

| ^

7 ^51 = 52

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

163
~7 = -8

Thc hin NOT ca biu thc biu din nh phn ca mt s nguyn b) Cu trc lp

SQL Server cung cp hai cu trc lp l: cu trc WHILE v GOTO. Cu trc lp WHILE: Cu lnh WHILE s kim tra iu kin trc khi thc hin lnh. Mt khi lnh l mt tp cc cu lnh c bao trong cp t kha BEGIN END. C php: WHILE Boolean_expression {sql_statement| statement_block} [BREAK] {sql_statement| statement_block} [CONTINUE] trong : + Boolean_expression: L biu thc iu kin kim tra iu kin lp. Vng lp s c thc hin khi biu thc tr v gi tr True v kt thc vng lp khi tr v gi tr False. + sql_statement|statement_block: l cu lnh SQL hoc khi cc cu lnh SQL s c lp li trong cu lnh While. Khi cc cu lnh SQL c bao trong cp t kha BEGIN END + BREAK: T kha dng ch nh dng vic thc thi vng lp hin ti. Tt c cc cu lnh sau t kha BREAK v trc t kha END s b b qua. + CONTINUE: T kha dng restart li vng lp hin ti ti v tr bt u. Tt c cc cu lnh sau t kha CONTINUE v trc t kha END s b b qua. V d 4.5. S dng cu trc lp WHILE n gin.
Use pubs go CREATE TABLE WhileLoopTest ( LoopID INT, Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

164

LoopValue VARCHAR(32) ) GO SET NOCOUNT ON DECLARE @intCounter INT DECLARE @vchLoopValue VARCHAR(32) SELECT @intCounter = 1 WHILE (@intCounter <= 100) BEGIN SELECT @vchLoopValue = 'Loop Interation #' + CONVERT (VARCHAR(4), @intCounter) INSERT INTO WhileLoopTest(LoopID, LoopValue) VALUES (@intCounter, @vchLoopValue) SELECT @intCounter = @intCounter + 1 END

Cu trc lp GOTO: Tng t nh cu trc WHILE, GOTO c th cho php lp mt chui cu lnh cho n khi iu kin c tha mn. Ch : Cu lnh GOTO khng nht thit phi s dng trong cc vng lp m c th s dng thot khi vng lp khc. s dng cu lnh GOTO, trc ht ta phi nh ngha mt nhn. Nhn l mt cu lnh ch nh v tr m cu lnh GOTO s nhy n. to nhn ta s dng c php sau:
LABLE:

nhy n nhn trong code ta s dng cu lnh GOTO theo c php sau:
GOTO LABLE

Trong : LABLE l nhn c nh ngha trc trong code. Bng vic s dng GOTO, ta c th nhy n mt v tr bt k trong code. V d 4.6. S dng cu trc lp GOTO n gin.
Use pubs Go CREATE TABLE GotoLoopTest ( GotoID INT, GotoValue VARCHAR(32) ) GO SET NOCOUNT ON

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL DECLARE DECLARE @intCounter @vchLoopValue

165 INT VARCHAR(32)

SELECT @intCounter = 0 LOOPSTART: SELECT @intCounter = @intCounter + 1 SELECT @vchLoopValue = 'Loop Iteration #' + CONVERT(VARCHAR(4), @intCounter) INSERT INTO GotoLoopTest(GotoID, GotoValue) VALUES (@intCounter, @vchLoopValue) IF (@intCounter <= 1000) BEGIN GOTO LOOPSTART END

c) Cu trc r nhnh Cu trc IFELSE: Cu trc IFELSE l mt khi cc cu lnh dng r nhnh da trn cc tham s c cung cp. C php ca khi cu lnh IF nh sau:
IF expression BEGIN sql_statements END [ELSE BEGIN sql_statements END]

Ch : Ta c th s dng cc cu trc IF lng nhau. V d 4.7. S dng cu trc r nhnh IF.


Use pubs Go CREATE PROCEDURE uspCheckNumber @intNumber INT AS IF @intNumber < 1 BEGIN PRINT 'Number is less that 1.' RETURN END ELSE IF @intNumber = 1 BEGIN PRINT 'One' RETURN END Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL ELSE IF @intNumber = 2 BEGIN PRINT 'Two' RETURN END ELSE IF @intNumber = 3 BEGIN PRINT 'Three' RETURN END ELSE IF @intNumber = 4 BEGIN PRINT 'Four' RETURN END ELSE IF @intNumber = 5 BEGIN PRINT 'Five' RETURN END ELSE IF @intNumber = 6 BEGIN PRINT 'Six' RETURN END ELSE IF @intNumber = 7 BEGIN PRINT 'Seven' RETURN END ELSE IF @intNumber = 8 BEGIN PRINT 'Eight' RETURN END ELSE IF @intNumber = 9 BEGIN PRINT 'Nine' RETURN END ELSE IF @intNumber = 10 BEGIN PRINT 'Ten' RETURN END ELSE BEGIN

166

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

167

PRINT 'Number is greater than 10.' RETURN END

Cu trc CASE: Cu trc ny c dng nh gi mt biu thc v tr v mt hoc mt s cc kt qu da vo gi tr ca biu thc. C 2 kiu cu trc CASE khc nhau nh sau: o Simple CASE: Vi cu trc ny, mt biu thc s c dng so snh vi mt tp cc gi tr xc nh kt qu. C php nh sau:
CASE case_expression WHEN expression THEN result [...n [ELSE else_result END

o Searched CASE: nh gi tp cc biu thc Boolean xc nh kt qu. C php ca n nh sau:


CASE WHEN Boolean_expression THEN result [...n [ELSE else_result END

Trong : + case_expression: Biu thc dng SQL Server nh gi gi tr trong cu lnh Simple CASE.
+ Expression: Gi tr dng so snh vi biu thc

case_expression nu ng th n s tr v kt qu. + Result: Kt qu s c tr v nu nh gi tr biu thc case_expression so vi Expression l ng.


+ Boolean_expression: SQL Server dng biu thc

Boolean r nhnh, nu biu thc nhn gi tr True th s thc hin kt qu Result. + else_result: Thc hin cc kt qu sau ELSE. V d 4.8. S dng cu trc r nhnh CASE dng trong c hai trng hp Simple Case v Searched Case.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL Use pubs Go

168

CREATE PROCEDURE uspCheckNumberCase @chrNumber CHAR(2) AS IF (CONVERT(INT, @chrNumber) < 1) OR (CONVERT(INT, @chrNumber) > 10) BEGIN SELECT CASE WHEN CONVERT(INT, @chrNumber) < 1 THEN 'Number is less than 1.' WHEN CONVERT(INT, @chrNumber) > 10 THEN 'Number is greater than 10.' END RETURN END SELECT CASE CONVERT(INT, @chrNumber) WHEN 1 THEN 'One' WHEN 2 THEN 'Two' WHEN 3 THEN 'Three' WHEN 4 THEN 'Four' WHEN 5 THEN 'Five' WHEN 6 THEN 'Six' WHEN 7 THEN 'Seven' WHEN 8 THEN 'Eight' WHEN 9 THEN 'Nine' WHEN 10 THEN 'Ten' END

d) Cu trc WAITFOR Cu trc WaitFor c dng ngn vic thc thi mt l, th tc, hay mt giao dch cho n mt thi im no hoc sau mt khong thi gian no . C php ca WAITFOR nh sau: WAITFOR { DELAY 'time' | TIME 'time' } Trong : + DELAY: Ch nh khong thi gian phi ch. Ti a l 24 gi. + TIME: Ch nh thi im thc thi mt l, th tc, hay mt giao dch.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

169

V d 4.9. S dng cu trc WAITFOR ch n lc 21h30 th thc hin xa bn ghi.


BEGIN WAITFOR TIME '21:30' DELETE FROM DMLOP WHERE MALOP='TH6A' END

V d 4.10. Xy dng th tc time_delay ch trong mt khong thi gian no v a ra thng bo khong thi gian ch .
CREATE PROCEDURE time_delay @DELAYLENGTH char(9) AS DECLARE @RETURNINFO varchar(255) BEGIN WAITFOR DELAY @DELAYLENGTH SELECT @RETURNINFO = 'A total time of ' + SUBSTRING(@DELAYLENGTH, 1, 2) + ' hours, ' + SUBSTRING(@DELAYLENGTH, 4, 2) + ' minutes, and ' + SUBSTRING(@DELAYLENGTH, 7, 2) + ' seconds ' + 'has elapsed! Your time is up.'; PRINT @RETURNINFO; END; GO -- This next statement executes the time_delay procedure. EXEC time_delay '00:05:00' GO

e) Cu trc TRYCATCH Trong SQL Server 2005, cu trc TRY CATCH c s dng qun l li tng t nh cc ngn ng lp trnh VB.NET, C# v C++. C php: BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH { sql_statement | statement_block } END CATCH[ ; ] Hot ng ca cu trc TRY CATCH: + Cu trc TRYCATCH gm hai phn: Khi TRY v khi CATCH. Khi mt iu kin li c d thy mt cu lnh Transact-SQL thuc khi TRY, iu khin c chuyn sang khi
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

170

CATCH x l. Sau khi khi CATCH iu khin ngoi l, iu khin c chuyn cho cu lnh Transact-SQL ngay sau lnh END CATCH. + Nu khng li trong khi TRY, iu khin c chuyn ngay lp tc cho cu lnh sau END CATCH. V d 4.11. S dng cu trc TRY CATCH iu khin li.
BEGIN TRY INSERT INTO [QLDiemSV].[dbo].[DMLOP]([MaLop],[TenLop], [Khoa]) VALUES ('TH6A','Tin hc 6A','6') END TRY BEGIN CATCH Print ERROR_MESSAGE() END CATCH

V d 4.11. Xy dng th tc a ra thng tin li.


USE QLDiemSV; GO BEGIN TRANSACTION; BEGIN TRY -- Generate a constraint violation error. DELETE FROM LOP WHERE MaLop='TH5A'; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() as ErrorState, ERROR_PROCEDURE() as ErrorProcedure, ERROR_LINE() as ErrorLine, ERROR_MESSAGE() as ErrorMessage; IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; END CATCH; IF @@TRANCOUNT > 0 COMMIT TRANSACTION; GO

f) Functions - Hm Hm c dng hoc l nh dng v thao tc d liu hoc l tr v thng tin cho ngi s dng. C hai loi hm: hm do h thng nh ngha
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

171

hoc hm do ngi dng nh ngha. Hm do h thng nh ngha c to do Microsoft v c ci t khi SQL Server ci t. Hm do ngi dng nh ngha c nh ngha bi ngi s dng bng cch s dng cu lnh CREATE FUNCTION . i vi loi hm ny ta s tho lun chng trong phn tip theo ca chng. Cc hm do h thng nh ngha c chia thnh cc kiu hm sau: String functions, Date functions, Mathematical functions, aggregate Functions, System functions,.v.v... String functions: L cc hm thao tc vi d liu kiu k t. Sau y l mt s hm thng dng. +
CHARINDEX(string1, string2, start_position):

Tm v tr bt u ca chui k t ch nh string1 trong chui string2 v bt u tm v tr start_position trong chui string2. V d 4.9. S dng hm CHARINDEX
SELECT CHARINDEX('test', 'This is a test', 1)

Hm s tr v gi tr 11, v tr bt u ca chui test trong chui 'This is a test'.


+ LEFT (string, number_of_characters):

Tr v

chui gm number_of_characters k t tnh t tri sang ca chui string. V d 4.10. S dng hm LEFT
SELECT LEFT(This is a test, 4)

Hm s tr v chui This
+ LEN(string): Xc nh di ca chui k t string.

V d 4.11. S dng hm LEN


SELECT LEN(This is a test)

Hm s tr v gi tr 14
+ LOWER(string): Hm tr v chui k t thng.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

172

V d 4.12. S dng hm LOWER


SELECT LOWER(This is a TEST)

Hm s tr v chui this is a test


+ LTRIM(string): Ct b cc k t trng bn tri ca

chui. V d 4.13. S dng hm LTRIM


SELECT LTRIM( This is a test )

Hm s tr v chui This is a test


+ RIGHT (string,

number_of_characters): tr v

chui gm number_of_characters k t tnh t phi sang ca chui string. V d 4.14. S dng hm RIGHT
SELECT RIGHT(This is a test, 4)

Hm s tr v chui test
+ RTRIM(string): Ct b cc k t trng bn phi ca chui.

V d 4.15. S dng hm RTRIM


SELECT RTRIM( This is a test )

Hm s tr v chui
+

This is a test

SUBSTRING ( expression ,start , length ): Hm

tr v chui con gm length k t ca expression tnh t v tr start.


SELECT x = SUBSTRING('abcdef', 2, 3) + UPPER(string): Chuyn i cc k thng thnh ch hoa.

V d 4.16. S dng hm UPPER


SELECT UPPER(This is a TEST)

Hm s tr v chui THIS IS A TEST Ch : Cn phi cn thn khi s dng cc hm, chng hn khi ta s dng hm UPPER trong v tri ca ton t so snh. Khi n s bt SQL Server

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

173

phi thc hin trn mt bng tm kim gi tr. Ta xt hai truy vn trong v d 4.17 sau:
select au_lname from authors where au_lname = Green select au_lname from authors where upper(au_lname) = Green

i vi truy vn th hai, s dng hm Upper mt thi gian lu hn so vi truy vn th nht. Date Functions: L cc hm lm vic vi d liu kiu datetime. Mt s hm lm vic vi cc kiu thng tin c bit c gi l datepart. Trc khi i vo cc hm, ta xt cc k hiu ca datepart cho trong bng 4.3. Bng 4.3. Cc thnh phn datepart K hiu datepart yy yyyy q qq m mm dy y d dd wk ww dw hh mi n ss datepart Year (nm) Year (nm) Quarter (qu) Quarter (qu) Month (thng) Month (thng) Dayofyear Dayofyear Day Day Week Week weekday hour Minute minute Second

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

174

s ms Sau y l mt s hm hay s dng:


+

Second millisecond

DATEADD (datepart, amount, date): Cng thm

mt s amount thi gian thnh phn datepart ca date. V d 4.17. S dng hm DATEADD
SELECT DATEADD(year, 1, GETDATE()))

Hm s tr v ngy hin ti cng thm mt nm.


+ DATEDIFF (datepart, date1, date2): So snh

im khc nhau gia hai ngy bng vic s dng tham s datepart. V d 4.18. S dng hm DATEDIFF
SELECT DATEDIFF(hour, 1/1/2008 12:00:00, 1/1/2008 16:00:00)

Hm s tr v gi tr 4. y l im khc nhau gia hai ngy, hai ngy chnh nhau 4 gi.
SELECT DATEDIFF(hour, 1/1/2008 12:00:00, 1/2/2008 16:00:00)

Hm s tr v gi tr 28. y l im khc nhau gia hai ngy, hai ngy chnh nhau 28 gi.
+ DATEPART(datepart, date): Hm tr v gi tr ca

thnh phn datepart trong date. V d 4.19. S dng hm DATEPART


SELECT DATEPART(month, 1/1/2008 16:00:00)

Hm s tr v gi tr thng 1.
+ DAY(date): Xc nh s ngy ca thng trong d liu

ngy gi date.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

175

V d 4.20. S dng hm DAY


SELECT DAY ('7/22/1979 00:04:00')

Hm s tr v gi tr ngy l 22. + + +
GETDATE(): Tr v gi tr ngy hin ti ca h thng. MONTH(date): Tng t nh hm DAY, hm MONTH

tr v thng ca d liu ngy gi.


YEAR(date): Tr v nm ca d liu ngy gi.

Mathematical Functions: Sau y ta trnh by mt s hm ton hc thng thng. + + + + + + ABS(number): Tr v gi tr tuyt i ca s number. CEILING(number): Tr v s nguyn nh nht ln hn hoc bng number.
FLOOR(number): Tr v s nguyn ln nht nh hn

hoc bng number. ROUND(number,precision): Hm lm trn s number ly precision ch s sau du thp phn. SQUARE(number): Hm tr v gi tr bnh phng s number. SQRT(number): Hm tr v gi tr cn bc hai s number. Aggregate Functions: Cc hm tp hp thc hin tnh ton trn mt tp hp cc gi tr v tr v mt gi tr n. Ngoi tr hm COUNT, hm tp hp b qua cc gi tr NULL. Cc hm tp hp thng s dng vi mnh GROUP BY trong khi cu lnh SELECT. Hm tp hp c php dng nh l cc biu thc trong trng hp: o Trong danh sch select ca khi cu lnh SELECT.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

176

o Trong mnh COMPUTE hoc COMPUTE BY . o Trong mnh HAVING Sau y l mt s hm tp hp hay c s dng: + AVG ([ALL|DISTINCT]expression): Hm tr v gi tr trung bnh ca tp cc gi tr trong mt nhm. ALL: p dng cho cc hm tp hp ch nh cho tt c cc gi tr. ALL l t kha mc nh. DISTINCT:Ch nh ch ly mt th hin duy nht ca mt gi tr. Ngha l trong tp hp c nhiu phn t c cng mt gi tr th ch ly mt gi tr i din cho n. V d 4.21. S dng hm AVG
USE pubs SELECT AVG(advance), SUM(ytd_sales) FROM titles WHERE type = 'business'

COUNT({[ALL|DISTINCT]expression]|*}): Hm tr v kiu int s cc phn t ca mt nhm. Ch . S dng hm COUNT


COUNT(*): Tr v s cc phn t trong mt nhm

bao gm c gi tr NULL v gi tr duplicates.


COUNT(ALL expression): Thc hin nh gi

tr cho expression ti mi dng trong nhm v tr v s cc gi tr khng NULL.


COUNT(DISTINCT

expression): Thc hin

nh gi tr cho expression ti mi dng trong nhm v tr v s cc gi tr duy nht v khng NULL. V d 4.22. S dng hm COUNT
USE pubs

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

177

GO SELECT COUNT(DISTINCT city) FROM authors GO

COUNT_BIG({[ALL|DISTINCT]expression}|*): Tr v s cc phn t trong mt nhm. Hm COUNT_BIG lm vic nh hm COUNT. im khc nhau gia chng l hm COUNT tr v gi tr kiu int cn hm COUNT_BIG tr v gi tr kiu bigint.

+ + +

MAX ([ALL|DISTINCT]expression): Tr v gi tr ln nht trong biu thc expression. MIN ([ALL|DISTINCT]expression): Tr v gi tr ln nht trong biu thc expression. SUM([ALL|DISTINCT]expression): Tr v tng ca tt c cc gi tr ca biu thc hoc tng cc gi tr DISTINCT ca biu thc expression. Hm SUM ch p dng cho cc ct kiu s. Cc gi tr NULL c b qua. V d 4.23. S dng hm SUM
USE pubs GO -- Aggregate functions SELECT type, SUM(price), SUM(advance) FROM titles WHERE type LIKE '%cook' GROUP BY type ORDER BY type GO

V d 4.24. S dng hm SUM tnh im trung bnh trong CSDL QLDiemSV


SELECT DIEM.Masv,(Convert(real, Sum( dbo.fncDiemCN(DiemL1,DiemL2)*MONHOC.SD

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

178

VHT))/convert(real,Sum(MONHOC.SDVHT))) AS DTB FROM DIEM INNER JOIN MONHOC ON DIEM.MAMH=MONHOC.MaMH GROUP BY DIEM.MaSV

System Functions: Cc hm h thng l cc hm ly thng tin h thng v cc i tng v thit lp trong SQL Server. + CONVERT i biu data_type. V d 4.25. S dng hm CONVERT
SELECT CONVERT(VARCHAR(5), 12345)

(data_type, thc

expression): Chuyn thnh kiu d liu

expression

Hm s tr v chui 12345. + + CAST (expression AS data_type): Chuyn i biu thc expression thnh kiu d liu data_type. CURRENT_USER: Tr v ngi s dng hin ti. V d 4.26. S dng hm CURRENT_USER
SELECT CURRENT_USER

+ +

DATALENGTH(expression): Tr v s byte c s dng trong biu thc expression. HOST_NAME(): tr v tn my tnh m ngi s dng hin ti ang login. V d 4.27. S dng hm HOST_NAME()
SELECT HOST_NAME()

SYSTEM_USER: Hm tr v tn ca cc User ang login h thng. V d 4.28. S dng hm SYSTEM_USER


SELECT SYSTEM_USER

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

179

USER_NAME(): Hm tr v username khi a s user ID. V d 4.29. S dng hm USER_NAME()


SELECT name FROM USER_NAME(uid) = 'dbo' sysobjects WHERE

4.2. Cc store procedure Cc th tc 4.2.1. Khi nim Store Procedure l mt tp cc pht biu T-SQL m SQL Server bin dch thnh mt k hoch thc thi n. Ln u tin khi SQL Server thc thi store procedure th n bin dch store procedure thnh k hoch v lu trong b nh m. Mi khi gi thc hin store procedure ny th n s dng li k hoch ny m khng phi bin dch li ln na. T- SQL store procedure tng t nh cc ngn ng lp trnh khc, chng chp nhn cc tham s nhp, tr v gi tr xut thng qua tham s hoc tr v thng ip cho bit th tc thnh cng hay tht bi. Cc ng dng c th giao tip vi SQL Server thng qua hai cch: + Chng trnh ng dng gi cc pht biu T-SQL t client n server. Cc pht biu ny c gi qua mng v c SQL Server bin dch li mi khi thc thi chng. + To store procedure, chng c lu v bin dch thnh mt k hoch server. Nh vy vi cch ny, s dng store procedure s gim c lu thng mng, hiu qu nhanh hn so vi cch gi cc pht biu T-SQL. 4.2.2. To store procedure C php: CREATE {PROC|PROCEDURE}[schema_name.] procedure_name [ ; number ] [{@parameter [type_schema_name.] data_type } [VARYING][= default ][[ OUT|OUTPUT ] [,...n ]

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

180

[ WITH <procedure_option> [ ,...n ] AS { [ BEGIN ] statements [ END ] } [;] <procedure_option> ::= [ ENCRYPTION ] [ RECOMPILE ] Trong : + procedure_name: l tn ca store procedure s c to. + parameter: L cc tham s truyn vo store procedure, ta phi nh ngha chng trong phn khai bo ca store procedure. Khai bo bo gm tn ca tham s (trc tn tham s s dng tin t @), kiu d liu ca tham s v mt s ch nh c bit ph thuc vo mc ch s dng ca tham s . + ; number: L s nguyn ty chn c s dng trong nhm cc th tc c cng tn. + data type: Kiu ca tham s trong phn khai bo. + [VARYING]: y l ty chn c ch nh khi cursor tr v nh mt tham s. + [= default] : Gn gi tr mc nh cho tham s. Nu khng gn gi tr mc nh th tham s nhn gi tr NULL. + OUTPUT: y l t kha ch nh tham s l tham s xut. Tham s xut khng dng c vi kiu d liu Text v image. + [,...n]: Ch nh rng c th khai bo nhiu tham s. + RECOMPILE:Ch nh Database Engine khng xy dng k hoch cho th tc ny v th tc s c bin dch ti thi im thc thi th tc. + ENCRYPTION:Ch nh SQL Server s m ha bn text lnh CREATE PROCEDURE. Users khng th truy cp vo cc bng h thng hoc file d liu truy xut bn text m ha.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

181

* Thc thi store procedure trong SQL Server: thc thi mt th tc trong SQL Server ta s dng c php sau: { EXEC | EXECUTE } { module_name [ ;number ]} [ [ @parameter = ] { value | @variable [ OUTPUT ] | [ DEFAULT ] } ] [ ,...n ] [ WITH RECOMPILE ] Trong : + module_name: L tn th tc cn thc hin. + ;number: Ch nh th tc trong nhm th tc cng tn. + @parameter: Tn tham s trong th tc. + @variable: Ch nh bin cha cc tham s hoc tr v tham s. + DEFAULT: Ch nh ly gi tr mc nh ca bin. V d 4.30. Xy dng th tc XemDSSV.
Use QLDiemSV Go IF EXISTS(Select name from sysobjects where name ='p_DSSV' and type='p') DROP PROCEDURE p_DSSV GO CREATE PROCEDURE p_DSSV AS SELECT MaSV, Hodem + ' '+TensV as Hoten, Ngaysinh, MaLop From HOSOSV GO

- Thc thi th tc p_DSSV


Use QLDiemSV Go EXEC p_DSSV Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

182

* Truyn tham s nhp vo trong store procedure. V d 4.32. Xy dng th tc pp_DSSV hin th danh sch sinh vin theo tham s m lp. M lp c truyn vo khi th tc c thc hin.
Use QLDiemSV Go IF EXISTS(Select name from sysobjects where name ='p_DSSV' and type='p') DROP PROCEDURE p_DSSV GO CREATE PROCEDURE p_DSSV @parMaLop Varchar(10)='TH%' AS SELECT MaSV, Hodem + ' '+TensV as Hoten, Ngaysinh From HOSOSV Where MaLop like @parMaLop GO

Gi thc thi th tc trn vi truyn gi tr cho tham s nhp nh sau:


EXEC p_DSSV TH03A EXEC p_DSSV @parMaLop=DEFAULT

* S dng tham s xut trong store procedure. V d 4.33. Xy dng th tc pp_Siso xut gi tr s s ca mt lp theo tham s m lp. M lp c truyn vo khi th tc c thc hin.
Use QLDiemSV Go IF EXISTS(Select name from sysobjects ='pp_Siso' and type='p') DROP PROCEDURE pp_Siso GO CREATE PROCEDURE pp_Siso @parMaLop Char(10), @parSiso Int OUTPUT AS SELECT @parSiso=count(*) From HOSOSV Where MaLop=@parMaLop GO DECLARE @siso int

where

name

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

183

exec pp_Siso 'TH03A',@parSiso=@siso OUTPUT Print 'Si so lop TH03A l :'+ convert(varchar(3),@siso) Go

Kt qu thc hin chng trnh:


Si so lop TH03A l :12

* S dng bin cc b: Cc bin cc b c s dng trong b lnh, trong chng trnh gi (Scipt) hoc trong th tc (xem v d 4.5 v 4.6). Bin cc b thng c gi cc gi tr s c kim tra trong pht biu iu kin v gi gi tr s c tr v bi lnh RETURN. Phm v ca bin cc b trong store procedure l t im bin c khai bo cho n khi thot store procedure. Ngay khi store procedure kt thc th bin khng c tham chiu na. C php khai bo bin cc b: DECLARE <parameter> [AS] <data type> Ging nh khai bo cc bin trn, trc tn bin phi c tin t @. Gi tr khi to ban u ca bin l NULL. thit lp gi tr ca bin ta s dng c php: SET <parameter> = <expression> SELECT <parameter> = <expression> * Cu lnh PRINT: Dng hin th chui thng bo ti ngi s dng. Chui thng bo ny n th di ti 8000 k t. C php ca lnh PRINT nh sau: PRINT < messages> * S dng SELECT tr v gi tr: Ta c th tr v gi tr bng vic s dng SELECT trong th tc hoc tr v kt qu thit lp t truy vn SELECT. V d 4.34. Xy dng th tc pp_Siso xut gi tr s s ca mt lp theo tham s m lp ra ngoi. M lp c truyn vo khi th tc c thc hin.
Use QLDiemSV Go

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

184

IF EXISTS(Select name from sysobjects where name ='pp_Siso' and type='p') DROP PROCEDURE pp_Siso GO CREATE PROCEDURE pp_Siso @parMaLop Char(10), @parSiso Int OUTPUT AS SELECT @parSiso=count(*) From HOSOSV Where MaLop=@parMaLop GO DECLARE @siso int exec pp_Siso 'TH03A',@parSiso=@siso OUTPUT SELECT 'Si so lop TH03A l :'= @siso Go

* Lnh RETURN: Ta c th s dng lnh RETURN thot khng iu kin khi th tc. Khi lnh RETURN c thc thi trong th tc, khi cc cu lnh sau RETURN trong th tc s b b qua v thot khi th tc tr v dng lnh tip theo trong chng trnh gi. Ngoi ra, ta c th s dng lnh RETURN tr v gi tr cho chng trnh gi, gi tr tr v phi l mt s nguyn, n c th l mt hng s hoc mt bin. C php nh sau: RETURN [ integer_expression ] V d 4.35. Cho CSDL pubs. Xy dng th tc usp_4_31 kim tra mt ch c tn ti trong bng titles hay khng? Nu tn ti mt ch th hin th ch . Nu khng tn ti ch th th tc tr v gi tr 1 hoc c nhiu hn mt ch th tr v gi tr 2.
Use pubs Go IF EXISTS(Select name from sysobjects where name ='usp_4_31' and type='p') DROP PROCEDURE usp_4_31 GO CREATE PROCEDURE usp_4_31 @vchTitlePattern VARCHAR(80) = '%' AS SELECT @vchTitlePattern = '%' + @vchTitlePattern + '%' IF (SELECT COUNT(*) FROM titles WHERE title LIKE @vchTitlePattern) < 1 BEGIN RETURN 1 END IF (SELECT COUNT(*) FROM titles WHERE title LIKE @vchTitlePattern) > 1 Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

185

BEGIN RETURN 2 END SELECT title, price FROM titles WHERE title LIKE @vchTitlePattern RETURN 0 GO DECLARE @intReturnValue INT EXEC @intReturnValue = usp_4_31 'Tin hoc' IF (@intReturnValue = 1) BEGIN PRINT 'There are no corresponding titles.' END IF (@intReturnValue = 2) BEGIN PRINT 'There are multiple titles that match this criteria. Please narrow your search.' END GO

4.2.3.Thay i, xa, xem ni dung store procedure a) Thay i store procedure C php: ALTER {PROC|PROCEDURE}[schema_name.] procedure_name [ ; number ] [{@parameter [type_schema_name.] data_type } [VARYING][= default ][[ OUT|OUTPUT ] [,...n ] [ WITH <procedure_option> [ ,...n ] AS { [ BEGIN ] statements [ END ] } [;] <procedure_option> ::= [ ENCRYPTION ] [ RECOMPILE ] V d 4.36. Ta sa li th tc p_DSSV trong v d 4.32 nh sau:
Use QLDiemSV Go ALTER PROCEDURE p_DSSV @parMaLop Char(10) AS SELECT MaSV, Hodem, TensV, Ngaysinh Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

186

GO

From HOSOSV Where MaLop=@parMaLop

b) Xa store procedure C php: DROP{ PROC|PROCEDURE}{[schema_name.] procedure } V d 4.37. Xa th tc p_DSSV:


Use QLDiemSV Go DROP PROCEDURE p_DSSV Go

c) Xem ni dung store procedure xem ni dung ca th tc ta s dng th tc h thng sp_helptext. V d 4.38. Xem ni dung th tc pp_DSSV:
Use QLDiemSV Go Exec sp_helptext pp_DSSV Go

Kt qu vic thi hnh cc cu lnh ny cho trong hnh 4.8.

Hnh 4.8. S dung th tc sp_helptext

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

187

4.3. Cc store function Cc hm 4.3.1. Cc khi nim Tt c cc ngn ng lp trnh, bao gm c T-SQL, vic c cc hm to cho cc ng dng tr ln mnh m. Ngoi ra, ngi lp trnh c th t to mt hm ring cho mnh lm cho h thng d c m rng. Mt hm - function - trong SQL Server c nh ngha l mt th tc n gin bao gm mt nhm cc cu lnh SQL 4.3.2. To cc hm Mt hm do ngi dng nh ngha c to bng cch s dng cu lnh CREATE FUNCTION theo c php sau: CREATE FUNCTION [owner_name.]function_name ( [ {@parameter_name scalar_data_type [= default]} [,...n] ] ) RETURNS scalar_data_type | TABLE(column_definition | table_constraint [,...n]) [WITH ENCRYPTION | SCHEMABINDING [,...n] ] [AS] [BEGIN function_body END] | RETURN [(] select_statement [)] Trong : + [owner_name.]: Ch nh tn i tng s s hu. Ta khng phi bt buc ch nh tn ngi s to i tng s hu n. + function_name: tn ca hm ta s to.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

188

+ parameter_name: L cc tham s Input cho hm. Cc tham s ny xy dng cng tng t nh trong stored procedure. + scalar_data_type: L kiu d liu v hng ca tham s. Mt hm c th nhn bt k kiu d liu no nh l tham s tr cc kiu timestamp, cursor, text, ntext, image. + default: Ch nh gi tr mc nh cho tham s, tng t nh trong stored procedure. + [,...n]: Ch nh mt hm c th to nhiu tham s. Mt hm trong SQL Server c th cha ti 1024 tham s. + RETURNS: t kha ny ch nh kiu d liu hm s tr v. Kiu d liu ca hm c th l mt kiu d liu v hng hoc mt bng. + scalar_data_type: Ta s ch nh kiu d liu nu nh hm tr v mt gi tr v hng. y ta phi ch nh kiu di d liu. + TABLE: y l kiu d liu cho php hm c th tr v nhiu dng d liu. + column_definition: nh ngha cc ct cho kiu d liu TABLE. Cc ct ny c nh ngha tng t nh nh ngha cc ct trong bng. + table_constraint: nh ngha cc rng buc trong kiu d liu TABLE ny. + [,...n]: Ch nh c th c nhiu ct v nhiu rng buc trong bng. + WITH ENCRYPTION: T kha ch nh code ca hm s c m ha trong bng syscomments. + SCHEMABINDING: T kha ny ch nh hm c to buc vo tt c cc i tng m n tham chiu.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

189

+ [,...n]: Ch dnh c th c nhiu t kha khc ngoi hai t kha trn. + AS: T kha cho bit code ca hm bt u. + BEGIN: i cng vi END to thnh bao khi bao cc cu lnh trong thn hm. + function_body: thn ca hm. + END: i cng vi BEGIN to thnh bao khi bao cc cu lnh trong thn hm. + RETURN: T kha ny s gi gi tr ti th tc gi hm. + select_statement: i km vi RETURN gi gi tr ti th tc gi hm. 4.3.3. Cc v d to cc hm V d 4.38. Xy Dng mt hm fncGetThreeBusinessDays tr v ngy lm vic th 3 tnh t ngy bt u @dtmDateStart.
CREATE FUNCTION fncGetThreeBusinessDays (@dtmDateStart DATETIME) RETURNS DATETIME AS BEGIN IF DATEPART(dw, @dtmDateStart) = 4 BEGIN RETURN(DATEADD(dw, 5, @dtmDateStart)) END ELSE IF DATEPART(dw, @dtmDateStart) = 5 BEGIN RETURN(DATEADD(dw, 5, @dtmDateStart)) END ELSE IF DATEPART(dw, @dtmDateStart) = 6 BEGIN RETURN(DATEADD(dw, 5, @dtmDateStart)) END

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

190

ELSE IF DATEPART(dw, @dtmDateStart) = 7 BEGIN RETURN(DATEADD(dw, 4, @dtmDateStart)) END RETURN(DATEADD(dw, 3, @dtmDateStart)) END

Thc hin th nghim hm trn, ta xy dng scipt sau:


DECLARE @dtmDate DATETIME SELECT @dtmDate = '1/10/2008' SELECT DATENAME(dw, @dtmDate) SELECT DATENAME(dw, dbo. fncGetThreeBusinessDays(@dtmDate))

V d 4.39. S dng hm fncGetThreeBusinessDays trn tnh ton trn mt ct trong mt bng.


CREATE TABLE OrderInfo ( OrderID INT NOT NULL, ShippingMethod VARCHAR(16) NOT NULL, OrderDate DATETIME NOT NULL DEFAULT GETDATE(), ExpectedDate AS( dbo.fncGetThreeBusinessDays(OrderDate) ) ) GO INSERT OrderInfo VALUES (1, 'UPS GROUND', GETDATE()) INSERT OrderInfo VALUES (2, 'FEDEX STANDARD', DATEADD(dd, 2, GETDATE())) INSERT OrderInfo VALUES (3, 'PRIORITY MAIL', DATEADD(dd, 4, GETDATE())) GO SELECT OrderID,ShippingMethod,CONVERT(VARCHAR(12), OrderDate,1) + '(' + DATENAME(dw, OrderDate) + ')' AS 'OrderDate', CONVERT(VARCHAR(12),ExpectedDate,1)+ '('+ DATENAME(dw, ExpectedDate) + ')' AS 'ExpectedDate' FROM OrderInfo

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

191

V d 3.40. Xy dng hm tr v cc dng d liu gm thng tin v im ca cc mn hc theo M lp.


CREATE FUNCTION fncBangDiem(@MaLop CHAR(10)) RETURNS @TableName TABLE ( MaSV CHAR(10), Hoten nvarchar(100), TenMH NVARCHAR(50), DiemL1 INT, DiemL2 INT )

AS BEGIN

INSERT INTO @TableName SELECT Di.MaSV, Ho.HoDem + ' '+ Ho.TenSV, Mo.TenMH, Di.DiemL1,Di.DiemL2 FROM DIEM Di JOIN HOSOSV Ho ON (Di.MaSV = Ho.MaSV) JOIN MONHOC Mo ON (Di.MaMH = Mo.MaMH) WHERE Ho.MaLop = @MaLop RETURN END GO

Th nghim gi hm ny trong on script chng trnh sau v kt qu cho trong hnh 4.10: Select * from fncBangDiem('TH03A')

Hnh 4.10. Gi hm fncBangDiem


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

192

V d 4.41. Xy dng hm a ra danh sch sinh vin ca mt lp ph thuc tham s m lp a vo.


CREATE FUNCTION fncDSSV(@MaLop CHAR(10)) RETURNS TABLE AS RETURN SELECT MaSV, HoDem + ' '+ TenSV As Hoten, NgaySinh FROM HOSOSV WHERE MaLop=@MaLop GO

Gi hm ny trong on script chng trnh sau: Select * from fncDSSV ('TH03A') 4.3.4.Thay i, xa, xem ni dung store function a) Thay i cc hm thay i cc hm ta dng cu lnh ALTER FUNCTION. ALTER FUNCTION [owner_name.]function_name ( [ {@parameter_name scalar_data_type [= default]} [,...n] ] ) RETURNS scalar_data_type | TABLE(column_definition | table_constraint [,...n]) [WITH ENCRYPTION | SCHEMABINDING [,...n] ] [AS] [BEGIN function_body END] | RETURN [(] select_statement [)] V d 4.42. Thay i hm fncDSSV
ALTER FUNCTION fncDSSV(@MaLop CHAR(10)) RETURNS TABLE AS RETURN Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

193

SELECT MaSV, HoDem + ' '+ TenSV As Hoten FROM HOSOSV WHERE MaLop=@MaLop GO

b) Xa hm xa hm ta dng cu lnh DROP FUNCTION. DROP FUNCTION { [ schema_name. ] function_name } V d 4.43. Xa hm fncDSSV
DROP FUNCTION fncDSSV

4.4. Trigger 4.4.1. Khi nim Trigger l m t ki u stored procedure c bi t c kch n (th c thi) m t cch t ng khi xy ra m t s ki n trn Database server v khng th th c thi b ng tay. Trigger c chia ra lm hai nhm: DML v DDL trigger. + DML triggers (hay Standart triggers) thc thi khi mt ngi s dng c gng sa i d liu thng qua s kin thao tc d liu (data manipulation language - DML) INSERT, UPDATE, hoc DELETE trn bng hoc view. DML triggers thng c s dng trong chnh sch m bo cc quy tc thng mi hoc m bo tnh ton vn d liu. + DDL triggers c thc thi p ng cc s kin nh ngha lc d liu (data definition language - DDL). Nhm lnh chnh ca cc lnh nh ngha lc d liu l CREATE, ALTER, v DROP. Nhm DDL trigger l nhm trigger mi c b xung trong SQL Server 2005 Database Engine. DML triggers c hai kiu, chng c x l khc nhau. Kiu ph bin vi mi ngi nht l kiu AFTER trigger v kiu th hai l INSTEAD OF trigger.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

194

AFTER Triggers: Khi cc cu lnh thay i d liu c thc hin trn mt bng c nh ngha trigger, mt vi x l xut hin trc khi trigger thc s n. u tin b truy vn s kim tra trn bng c bt c cc rng buc no hay khng. Nu c, SQL Server s tin hnh kim tra tnh hp l ca d liu trn mi rng buc no. Nu d liu ang thm vo hoc ang sa i m khng tha cc rng buc th b truy vn s dng cu lnh trn v khi trigger s khng c kch n. Ngc li, khi kim tra thnh cng th cc trigger s c thc thi. Trc khi bt c cu lnh no cha trigger thc s c thc hin, SQL Server to ra hai bng c bit lu trong b nh c cng cu trc vi bng m trn trigger c to. + Table INSERTED cha cc gi tr ang c Add vo bng. + Table DELETED cha cc gi tr ang b xa t bng. Nu trigger c nh ngha l INSERT trigger th SQL Server s ch to bng INSERTED, cn nu l DELETE trigger th th SQL Server s ch to bng DELETED. Cui cng l nu trigger c nh ngha l UPDATE trigger th SQL Server s to c hai bng v INSERTED s cha nh ca hng sau khi thay i cn bng DELETED cha nh ca hng trc khi thay i. INSTEAD OF trigger: L mt c im thm vo ca SQL Server 2000. Nh tn gi m ch, INSTEAD OF trigger c kch n thay cho hnh ng c s dng kch n. Ngha l, nu mt trigger c nh ngha l INSTEAD OF INSERT trigger th trigger ny s c n khi cu lnh Insert c thc hin trn bng. Sau khi cu lnh sa i d liu c gi i th INSTEAD OF trigger c kch n v hin lp tc ngay lp tc. Cc rng buc khng c kim tra trc khi trigger c kch n, mc d cc bng INSERTED, DELETED vn c to. Sau khi cc bng ny c to th qu trnh x l trigger tng t nh qu trnh x l ca stored procedure. INSTEAD OF trigger c th c to trn bng hoc trn view.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

195

4.4.2. To trigger a) Dng T-SQL to trigger Ta dng T-SQL to trigger theo c php sau: - To DML Trigger: CREATE TRIGGER trigger_name ON {table | view } [WITH ENCRYPTION] { {{FOR | AFTER | INSTEAD OF} { [DELETE] [,] [INSERT] [,] [UPDATE] } [NOT FOR REPLICATION] AS [ { IF UPDATE ( column ) [ { AND | OR } UPDATE ( column ) ] [ ...n ] | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask ) { comparison_operator } column_bitmask [ ...n ] } ] sql_statement [ ...n ] } Trong : + trigger_name: tham s ch nh tn ca trigger s to. + ON: Ch nh ly tn ca bng hoc view m ta s xy dng trigger trn . + table | view: Tn ca bng hoc ca view. + WITH ENCRYPTION: Dng ch nh code ca trigger m ha lu tr trn bng syscomments m ngi khc khng th xem code ca trigger . + FOR: nh ngha hnh ng m trigger c kch n v kiu ca trigger ta ang to. AFTER trigger s l trigger mc nh nu ch c ch nh FOR.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

196

+ AFTER: Ch nh AFTER trigger. Ty chn ny ch nh ring khng ln vi t kha INSTEAD OF. AFTER triggers khng c nh ngha trn view. + INSTEAD OF: T kha ch nh y l INSTEAD OF trigger. Ty chn ny ch nh khng ln vi t kha AFTER. + DELETE: Ch nh rng trigger ta ang to s c kch n p ng vi hnh ng DELETE ca bng hoc view. + INSERT: Ch nh rng trigger ta ang to s c kch n p ng vi hnh ng INSERT ca bng hoc view. + UPDATE: Ch nh rng trigger ta ang to s c kch n p ng vi hnh ng UPDATE ca bng hoc view. + NOT FOR REPLICATION: Ch nh rng bt c bn sao no ca cc hnh ng chy ngm di bng ny u khng c kch n trigger ny. + AS: Ch nh phn code ca trigger bt u t y. + IF UPDATE (column): c dng trong cc trigger INSERT, UPDATE. Cu trc ny c dng kim tra cc sa i trn ct ch nh v sau l cc hnh ng trn n. + {AND | OR} UPDATE (column): Ch nh rng ta c th s dng chui cc cu trc UPDATE vi nhau kim tra mt vi ct ti cng mt thi im. + ...n: Ch nh ta c th lp li cc cu trc trn nu cn thit. + IF(COLUMNS_UPDATED():Ch dng trong cc trigger INSERT, UPDATE. Hm tr v mt bit ch nh ct b chnh sa trong qu trnh INSERT, UPDATE trn bng c s. + bitwise_operator: c dng so snh vi bit tr v ca hm COLUMNS_UPDATED()
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

197

+ updated_bitmask: c s dng kim ct no thc s c Update trong cu lnh Insert hoc Update. + sql_statement: Cc cu lnh T-SQL + ... n: Ch nh lp li cc cu lnh T-SQL. - To DDL Trigger: CREATE TRIGGER trigger_name ON { ALL SERVER | DATABASE } [ WITH ENCRYPTION ] { FOR |AFTER } {event_type } [,...n ] AS { sql_statement [ ; ] [ ...n ]} Trong : + DATABASE:Ch nh phm vi ca DDL trigger l database hin thi. Trigger s kch n khi s kin event_type xy ra trn database hin thi. + ALL SERVER: Ch nh phm vi ca DDL trigger l server hin thi. Trigger s kch n khi s kin event_type xy ra trn server hin thi. + event_type: L tn ca s kin m l nguyn nhn kch n DDL trigger. Cc s kin ny c th l: CREATE_FUNCTION, CREATE_INDEX, GRANT_DATABASE, CREATE_TABLE, ALTER_VIEW, ALTER_TABLE, DROP_TABLE, DROP_VIEW, .v.v... V d 4.44. To mt AFTER INSERT Trigger. Trong v d ny ta nh ngha AFTER INSERT Trigger trn bng TriggerTableChild. Trigger ny c nhim v kim tra xem c s tng ng vi cc dng ca bng TriggerTableParent hay khng. Nu khng c s tng ng n s thc hin roll back (cun li) li giao dch v dng thng bo li hin ln. Nu c s tng ng th giao dch c thc hin mt cch bnh thng.
CREATE TABLE TriggerTableParent ( TriggerID INT,

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL TriggerText ) GO INSERT INSERT INSERT INSERT INSERT GO INTO INTO INTO INTO INTO

198

VARCHAR(32)

TriggerTableParent TriggerTableParent TriggerTableParent TriggerTableParent TriggerTableParent

VALUES VALUES VALUES VALUES VALUES

(1, (2, (3, (4, (5,

'Trigger 'Trigger 'Trigger 'Trigger 'Trigger

Text Text Text Text Text

1') 2') 3') 4') 5')

CREATE TABLE TriggerTableChild ( TriggerID INT, TriggerSubText VARCHAR(32) ) GO CREATE TRIGGER trTriggerTableChildInsert ON TriggerTableChild FOR INSERT AS IF (SELECT COUNT(*)FROM TriggerTableParent TTP INNER JOIN INSERTED I ON (TTP.TriggerID= I.TriggerID))= 0 BEGIN ROLLBACK TRANSACTION RAISERROR ('No corresponding record was found in the TriggerTableParent table for this insert.', 11, 1) END ELSE Print 'This vas inserted' GO SET NOCOUNT ON INSERT INTO TriggerTableChild VALUES(1, 'Sub Trigger Text 1') INSERT INTO TriggerTableChild VALUES(2, 'Sub Trigger Text 2') INSERT INTO TriggerTableChild VALUES(3, 'Sub Trigger Text 3') INSERT INTO TriggerTableChild VALUES(6, 'Sub Trigger Text 6') GO

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

199

V d 4.45. Dng bng INSERTED v DELETED


CREATE TRIGGER trTriggerTableParentUpdate1 ON TriggerTableParent1 AFTER UPDATE AS SET NOCOUNT ON PRINT SELECT FROM PRINT SELECT FROM 'Contents of the INSERTED Table:' * INSERTED 'Contents of the DELETED Table:' * DELETED

PRINT 'Contents of the TriggerTableParent Table:' SELECT TTP.* FROM TriggerTableParent1 TTP INNER JOIN INSERTED I ON (TTP.TriggerID = I.TriggerID) ROLLBACK TRANSACTION GO UPDATE TriggerTableParent1 SET TriggerText = 'Changed Trigger Text 1' WHERE TriggerID = 1

Khi s dng lnh UPDATE, kt qu cho thy bng INSERTED cha cc gi tr mi; bng DELETED cha cc gi tr c v bng TriggerTableParent1 cha cc gi tr mi. V d 4.46. S dng cu trc IF UPDATED trong UPDATE Trigger
CREATE TRIGGER trTriggerTableChildUpdate ON TriggerTableChild1 AFTER UPDATE AS IF UPDATE(TriggerID) BEGIN IF (SELECT COUNT(*)FROM TriggerTableParent1 TTP INNER JOIN INSERTED I ON (TTP.TriggerID = I.TriggerID)) = 0 Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

200

BEGIN RAISERROR ('No parent record exists for this modification. Transaction cancelled.', 11, 1) ROLLBACK TRANSACTION RETURN END END GO UPDATE TriggerTableChild1 SET TriggerID = 7 WHERE TriggerID = 1 GO

V d 4.47. To INSTEAD OF Trigger. Bi v INSTEAD OF Trigger c kch n trc khi bt c d liu no c sa i trong CSDL, do vai tr ca hai bng INSERTED v DELETED b gim nh hn. Ta xt v d sau tng t nh v d 4.45.
CREATE TABLE TriggerTableParent2 ( TriggerID INT, TriggerText VARCHAR(32) ) GO INSERT INTO TriggerTableParent2 VALUES(1,'Trigger Text INSERT INTO TriggerTableParent2 VALUES(2,'Trigger Text INSERT INTO TriggerTableParent2 VALUES(3,'Trigger Text INSERT INTO TriggerTableParent2 VALUES(4,'Trigger Text INSERT INTO TriggerTableParent2 VALUES(5,'Trigger Text GO CREATE TABLE TriggerTableChild2 ( TriggerID INT, TriggerSubText VARCHAR(32) ) GO CREATE TRIGGER trTriggerTableParent2InsteadOfUpdate ON TriggerTableParent2 Bin son: Chu Th Hng B mn: Cc h thng thng tin

1') 2') 3') 4') 5')

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL INSTEAD OF UPDATE AS SET NOCOUNT ON

201

PRINT 'Contents of the INSERTED Table:' SELECT * FROM INSERTED PRINT 'Contents of the DELETED Table:' SELECT * FROM DELETED PRINT 'Contents of the TriggerTableParent Table:' SELECT TTP.* FROM TriggerTableParent2 TTP INNER JOIN INSERTED I ON (TTP.TriggerID = I.TriggerID) ROLLBACK TRANSACTION GO UPDATE TriggerTableParent2 SET TriggerText = 'Changed Trigger Text 1' WHERE TriggerID = 1 GO

Khi thc hin lnh Update, ta thy bng c s cha c chn d liu do trigger c thc thi trc khi c s sa i d liu, y chnh l c im ca INSTEAD OF Trigger. C th khi s dng lnh UPDATE, kt qu cho thy bng INSERTED cha cc gi tr mi; bng DELETED cha cc gi tr c v bng TriggerTableParent2 cha cc gi tr c. V d 4.48. View ca cc bng v INSTEAD OF Trigger. Mt trong nhng c im ni bt chnh ca INSTEAD OF Trigger l cho php ngi s dng thc hin cc cu lnh thay i d liu trn view ca nhiu bng. Trong v d ny, ta xy dng mt INSTEAD OF Trigger thc hin chc nng ny.
SET NOCOUNT ON GO CREATE TABLE ViewTable1 Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL (

202

KeyColumn INT, Table1Column VARCHAR(32) ) GO INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT GO

INTO INTO INTO INTO INTO INTO INTO INTO INTO INTO

ViewTable1 ViewTable1 ViewTable1 ViewTable1 ViewTable1 ViewTable1 ViewTable1 ViewTable1 ViewTable1 ViewTable1

VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES

(1, 'ViewTable1 Value 1') (2, 'ViewTable1 Value 2') (3, 'ViewTable1 Value 3') (4, 'ViewTable1 Value 4') (5, 'ViewTable1 Value 5') (6, 'ViewTable1 Value 6') (7, 'ViewTable1 Value 7') (8, 'ViewTable1 Value 8') (9, 'ViewTable1 Value 9') (10, 'ViewTable1 Value 10')

CREATE TABLE ViewTable2 ( KeyColumn INT, Table2Column VARCHAR(32) ) GO INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT GO INTO INTO INTO INTO INTO INTO INTO INTO INTO INTO ViewTable2 ViewTable2 ViewTable2 ViewTable2 ViewTable2 ViewTable2 ViewTable2 ViewTable2 ViewTable2 ViewTable2 VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES (1, 'ViewTable2 Value 1') (2, 'ViewTable2 Value 2') (3, 'ViewTable2 Value 3') (4, 'ViewTable2 Value 4') (5, 'ViewTable2 Value 5') (6, 'ViewTable2 Value 6') (7, 'ViewTable2 Value 7') (8, 'ViewTable2 Value 8') (9, 'ViewTable2 Value 9') (10, 'ViewTable2 Value 10')

CREATE VIEW TestView1 AS SELECT VT1.KeyColumn, VT1.Table1Column, VT2.Table2Column

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

203

FROM ViewTable1 VT1 INNER JOIN ViewTable2 VT2 ON (VT1.KeyColumn = VT2.KeyColumn) GO INSERT INTO TestView1 VALUES (11, 'ViewTable1 Value 11', 'ViewTable2 Value 11') GO CREATE TRIGGER trTestView1InsteadOfInsert ON TestView1 INSTEAD OF INSERT AS DECLARE @intKeyColumn INT DECLARE @vchTable1Column VARCHAR(32) DECLARE @vchTable2Column VARCHAR(32) DECLARE @intError INT SET NOCOUNT ON SELECT @intKeyColumn=KeyColumn, @vchTable1Column = Table1Column, @vchTable2Column = Table2Column FROM INSERTED BEGIN TRANSACTION INSERT INTO ViewTable1 VALUES(@intKeyColumn,@vchTable1Column) SELECT @intError = @@ROWCOUNT INSERT INTO ViewTable2 VALUES(@intKeyColumn, @vchTable2Column) SELECT @intError = @intError + @@ROWCOUNT IF ((@intError < 2) OR (@intError % 2) <> 0) BEGIN RAISERROR('An error occurred during the multitable insert.', 1, 11) ROLLBACK TRANSACTION RETURN END COMMIT TRANSACTION GO INSERT INTO TestView1 VALUES (11, 'ViewTable1 Value 11','ViewTable2 Value 11') GO

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

204

Trong on script trn, u tin ta to 2 bng v chn 10 dng vo hai bng . Hai bng c chung mt ct l KeyColumn v ta to view th hin d liu ca hai bng. Lnh INSERT s thc hin chn d liu vo hai bng. Lnh INSERT u tin s b li v c nhiu bng trong mnh FROM ca cu lnh SELECT to view . Lnh tip theo s c thc hin bi trigger to. * Tin trnh x l giao dch - TRANSACTION: DBMS phi m bo mt giao dch c x l nh mt n v c s. iu ny c ngha l khi DBMS ang thc hin tin trnh x l cu lnh u tin trong mt giao dch th th tin trnh ny phi c tip tc cho n khi tt c cc cu lnh trong giao dch c thc hin thnh cng, giao dch ny khng b b gy. Tt c cc cu lnh trong mt giao dch phi c x l nh mt n v cng vic. Khi mt tin trnh b b gy gia mt giao dch, nh kt qu ca vic re boot, h thng b v, th DBMS phi a database v trng thi tn ti trc khi giao dch c bt u. Mt cu lnh SQL c bit lm iu ny l ROLL BACK. Nu tt c cu lnh trong c thc hin thnh cng th s thay i Database c thc hin bi cu lnh COMMIT. COMMIT v ROLL BACK l cc cu lnh SQL thao chun ANSI/ISO, ging nh cc cu lnh SELECT, INSERT, .v.v... V d 4.49. DDL Trigger. CREATE TRIGGER safety ON DATABASE FOR DROP_TABLE, ALTER_TABLE AS PRINT 'You must disable Trigger "safety" to drop or alter tables!' ROLLBACK 4.4.3. Cc thao tc qun l trigger * Xem m trigger: Dng th tc sp_helptext. V d 4.49. Xem code ca trigger trTestView1InsteadOfInsert Exec sp_helptext trTestView1InsteadOfInsert go
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

205

* Xem nhng trigger no ang tn ti trn mt bng hoc mt view: Dng th tc sp_helptrigger. V d 4.50. Xem cc trigger trn bng HOSOSV Use QLDiemSV Go Exec sp_helptrigger HOSOSV go * Thay i ni dung trigger: thay i trigger ta dng cu lnh ALTER TRIGGER theo c php sau: - Sa DML Trigger: ALTER TRIGGER trigger_name ON {table | view } [WITH ENCRYPTION] { {{FOR | AFTER | INSTEAD OF} { [DELETE] [,] [INSERT] [,] [UPDATE] } [NOT FOR REPLICATION] AS [ { IF UPDATE ( column ) [ { AND | OR } UPDATE ( column ) ] [ ...n ] | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask ) { comparison_operator } column_bitmask [ ...n ] } ] sql_statement [ ...n ] } - Sa DDL Trigger: ALTER TRIGGER trigger_name ON { ALL SERVER | DATABASE } [ WITH ENCRYPTION ] { FOR |AFTER } {event_type } [,...n ] AS { sql_statement [ ; ] [ ...n ]}

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

206

V d 4.51. Thay i ni dung trigger trTestView1InsteadOfInsert


ALTER TRIGGER trTestView1InsteadOfInsert ON TestView1 INSTEAD OF INSERT AS DECLARE @intKeyColumn INT DECLARE @vchTable1Column VARCHAR(32) DECLARE @vchTable2Column VARCHAR(32) DECLARE @intError INT SET NOCOUNT ON SELECT @intKeyColumn=KeyColumn, @vchTable1Column = Table1Column, @vchTable2Column = Table2Column FROM INSERTED BEGIN TRANSACTION INSERT INTO ViewTable1 VALUES(@intKeyColumn,@vchTable1Column) SELECT @intError = @@ROWCOUNT INSERT INTO ViewTable2 VALUES(@intKeyColumn, @vchTable2Column) SELECT @intError = @intError + @@ROWCOUNT IF ((@intError < 2) OR (@intError % 2) <> 0) BEGIN ROLLBACK TRANSACTION RETURN END COMMIT TRANSACTION GO

* Xa mt trigger: Dng cu lnh DROP TRIGGER. - Xa DML Trigger: DROP TRIGGER schema_name.trigger_name [ ,...n ] - Xa DDL Trigger: DROP TRIGGER trigger_name [ ,...n ] ON { DATABASE | ALL SERVER }

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

207

V d 4.52. Xa trigger trTestView1InsteadOfInsert


DROP TRIGGER trTestView1InsteadOfInsert go

* V hiu ha hoc lm cho c hiu lc mt trigger ta dng cu lnh: DISABLE | ENABLE TRIGGER{[ schema . ] trigger_name [ ,...n ] | ALL } ON { object_name | DATABASE | ALL SERVER } [ ; ] V d 4.53. V hiu ha trigger trTriggerTableParent2InsteadOfUpdate Trn bng TriggerTableParent2.
ALTER TABLE TriggerTableParent2 DISABLE TRIGGER trTriggerTableParent2InsteadOfUpdate GO.

V d 4.54. V hiu ha trigger [trTriggerTableChildInsert] trn bng TriggerTableChild. DISABLE TRIGGER [trTriggerTableChildInsert] [dbo].[TriggerTableChild] V d 4.55. Lm cho trigger trTriggerTableParent2InsteadOfUpdate trn bng TriggerTableParent2 c hiu lc.
ALTER TABLE TriggerTableParent2 ENABLE TRIGGER trTriggerTableParent2InsteadOfUpdate GO.

ON

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

208

Chng 5. SQL SERVER V LP TRNH NG DNG 5.1. M hnh kt ni ng dng n SQL server 5.1.1. M hnh ADO ADO l phng thc truy xut d liu c ca Microsoft, v n tr thnh chun cho cc mi trng Office, Web, v Visual Basic trc .NET. Sau y l cc sn phm pht trin ca ADO: + Microsoft Office 200x + Visual Studio 6.0 (bao gm tt c cc ngn ng trong ) + SQL Server 7.0, 2000 Data Access Objects (DAO), l chun trc ADO, c s dng trong Office v Visual Basic, nhng n khng c thit k s dng trong cc mi trng Web nh Visual InterDev v cc d liu servers khc. Do ADO cho n by gi ang l chun pht trin cc ng dng.
Cc m hnh i tng ADO (ADO Object Models)

y l cc m hnh i tng, mang ngha s nhiu. Khng nh DAO ch bao gm mt m hnh i tng (one object model), ADO c phn chia thnh cc m hnh i tng (object models). Cc m hnh i tng ca ADO lm vic vi nhau a ra cc objects v cc collections cn thit ta lm vic vi d liu. Trong ADO c cp m hnh i tng: + ActiveX Data Objects 2.7 (ADODB) cho php ta to v lm vic vi recordsets cng nh thc hin qun l li. + ADO Extensions 2.7 for DDL and Security (ADOX) l ngn ng nh ngha d liu, cho php ta lm vic v sa i lc CSDL (database schema) v bo mt cc i tng Tuy nhin, cc i tng ny s c s dng kt hp vi nhau. Chng hn, khi mun sa i cu trc mt bng th ta cn th vin ADOX, nhng

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

209

n hot ng th ta cn ADODB. Cc ng dng thng lm vic vi cc bn ghi d liu. ActiveX Data Objects 2.7 (ADODB) Object Model M hnh i tng ActiveX Data Objects - ADO (Xem hnh 5.1) bao gm:

Hnh 5.1. M hnh ADO + i tng Connection. Tng t nh i tng Database trong DAO, l ni m tt c cc thao tc lm vic ca ta vi ADO c bt u. Tt c cc objects v collections u c cp sau i tng Connection. + i tng Errors collection/Error. Ging nh DAO errors collection v error object, n cho php pht trin qun l li. + i tng Command. Cho php chy truy vn trn mt database v tr li cc bn ghi trn i tng Recordset, thao tc vi cu trc CSDL, v thc hin mt thao tc d liu. Mt tp hp cc tham s s c s dng vi i tng Command.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

210

+ Recordset object. Tng t nh DAO Recordset object, ta c th m cc i tng Recordset ch c hoc to bng ng. Mi i tng Recordset c mt tp cc trng (Field). + Stream object. i tng ny cho php ta c cy c bit cu trc phn cp (special tree-structured hierarchies), nh e-mail messages hoc cc file h thng. 5.1.2. M hnh ADO.NET ADO.NET c thit k cung cp kin trc ri rc (disconnected architecture). C ngha l cc ng dng connect ti database truy np d liu v lu tr trong memory. Sau disconnect vi database v s dng b nh sao chp (memory copy) ca d liu . Nu nh database cn phi c update vi cc thay i trn memory copy, mt kt ni mi (connection) c hnh thnh v database c update. B nh chnh lu tr d liu l DataSet, ni m cha cc b nh lu tr d liu khc, nh l: Cc i tng DataTable; ta c th lc v sp xp d liu trn DataSet bng vic s dng cc i tng DataView. Vic s dng kin trc disconnected architecture cung cp rt nhiu li ch, trong , quan trng nht l cho php ng dng tr ln scale up. Ngha l database ca ta s thc thi tt nh h tr hng trm users tuy n ch h tr vi chc users. iu c th bi v ng dng connects ti database ch truy np hoc update d liu, bng cch gii phng cc connections v database sn c cho cc th hin khc ca ng dng hoc cc ng dng khc s dng cng database. Cc i tng trong ADO.NET i tng chnh c s dng trong ADO.NET l i tng DataSet. Ta c th thy i tng DataSet v cc thuc tnh, cc phng thc, v cc i tng ca n trong hnh 5.2 di y.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

211

Hnh 5.2. M hnh ADO.NET Xt bng Bng 5.1 tm hiu cc m t ngn ngn v cc i tng hay dng.
Bng5.1. ADO.NET Data Objects hay c dng thao tc d liu

Object

Mc ch

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

212

DataSet

i tng ny c s dng cng vi cc iu khin d liu khc, lu tr cc kt qu c tr v bi cc i tng commands v data adapters. Khng nh recordset ca ADO v DAO, Data set thc s mang li mt view phn cp ca d liu. Bng vic s dng cc thuc tnh v cc collections trong i tng DataSet, ta c th nhn c ton b cc quan h (relations), cc tables ring bit, rows, v columns.

DataTable

Mt trong i tng ca data set, l i tng DataTable cho php ta c th thao tc d liu trong mt table ring bit. Data table tng t nh i tng recordset trong ADO.

DataView

Bng vic s dng i tng ny, ta c th lc v sp xp d liu, duy tr cc views khc nhau ca d liu. Mi data table c mt default view, n l ni khi ng data view m c th c sa di v lu tr trong data view khc. i tng ny cho php ta thao tc cc rows ca d liu trong data tables. N c th c xt nh mt cache ca d liu m ta c th thc hin cc thao tc adding, deleting, v modifying records. Ta c th quay tr li recordset, ni m ta s chy cc cu lnh SQL update d liu v server. Nh tn ngh, ta c th nhn cc thng tin ti cc ct bng vic s dng i tng DataColumn. Ta c th ly thng tin lc nh l d liu bng vic s dng i tng ny. V d: nu ta mun to mt list box ca tn cc trng, ta c th lp thng qua tp DataColumn ca cc dng d liu v truy lc tt c cc tn trng.

DataRow

DataColumn

PrimaryKey

i tng ny cho php ta ch nh primary key cho table d liu. Cch khc, khi ta s dng phng thc Find ca data table.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

213

.NET cng cung cp cc classes, c gi data providers, s dng tn min (namespaces) lm vic vi cc i tng ADO.NET v cung cp cc truy xut vi d liu. Li ca cc lp ADO.NET tn ti trong namespace System.Data. Namespace ny cha mt vi namespaces con. Phn quan trng nht ca chng l cc tn min System.Data.SqlClient v System.Data.OleDb. Chng cung cp cc classes s dng cho vic truy cp SQL Server databases v OLE (Object Linking and Embedding) DB- compliant databases (phc hi d liu). Cc lp ca OleDb v SqlClient cho trong hnh 5.3. v Bng 5.2. m t vn tt cc i tng thng c s dng thao tc vi d liu.

Hnh 5.3. OleDb v SqlClient classes A O


Bng 5.2. .NET Data Provider Classes thng c s dng thao tc d liu

Object
Command

Mc ch Tng t nh i tng ADO Command, cho php ta thc hin cc stored procedures trong code. Khc vi phin bn ADO, ta c th to i tng DataReader bng vic s dng phng thc ExecuteReader.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL


Connection

214

y l i tng m kt ni ti server v database m ta mun lm vic. Khc vi i tng ADO Connection, cch thc kt ni ph thuc vo i tng m ta mun lm vic, nh l i tng DataReader hay DataSet.

DataAdapter

i tng DataAdapter cho php ta to cc cu lnh SQL v in d liu vo datasets. N cng cho php to cc action queries cn thit, nh l Insert, Update, v Delete.

DataReader

i tng ny to mt read-only, forward-only stream ca d liu m cho php chng t trn cc iu khin, nh ListBox v ComboBox.

Parameter

y l i tng cho php ch nh cc tham s m cc i tng DataAdapter c th ch nh v s dng

Ngoi ra, hai tn min con khc cng tn ti trong tn min System.Data, l: System.Data.OracleClient v System.Data.Odbc. Trong , namespace System.Data.OracleClient c s dng dnh cho cc CSDL Oracle. Cc lp SqlClient cung cp cc kt qu tt nht khi lm vic vi cc SQL Server databases; OracleClient cung cp thc thi ti u khi truy cp vo Oracle databases. Namespace System.Data.Odbc cung cp truy cp ti ODBC (Open Database Connectivity) data sources c m khng c support bi cng ngh OleDb. Nh vy, cc tn min System.Data.SqlClient, System.Data.OleDb, System.Data.OracleClient, v System.Data.Odbc c bit nh l data providers trong ADO.NET. Trong mn hc, ta xy dng ng dng truy xut SQL Server databases nn s dng namespace SqlClient. Tuy nhin trong ADO.NET, cc data providers khc nhau lm vic theo mt cch thc tng t nhau. V vy cc k xo ta s dng y c th c d dng chuyn giao cho cc lp OleDb classes. Vi ADO.NET, ta s dng data provider ny l ph hp nht cho

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

215

data source ca ta. Ta khng cn thit phi hc tt c cc interface mi, bi v tt c cc data providers lm vic theo mt cch thc tng t nhau.

5.1.3. im khc nhau gia ADO v ADO.NET + ADO lm vic vi kt ni d liu (connected data). Ngha l khi truy cp d liu, chng hn nh viewing hoc updating d liu, th n l thi gian thc (real-time), vi mt kt ni c s dng trong sut thi gian . + ADO.NET s dng d liu theo kiu disconnected. Khi truy cp d liu, ADO.NET to bn copy ca d liu bng vic s dng XML. ADO.NET ch chim gi vi vic m mt kt ni trong khong thi gian y d liu vo hoc thc hin bt c yu cu updates no. Vi iu ny, lm cho ADO.NET rt hu hiu cho cc ng dng Web. N cng tt cho cc ng dng desktop. + ADO c mt i tng chnh c dng tham chiu d liu, c gi l Recordset object. V c bn i tng ny a ra mt bng view n ca d liu, tuy nhin l ta c th kt ni cc bng to mt tp cc bn ghi mi. Vi ADO.NET, ta c nhiu i tng khc nhau cho php truy xut d liu theo cc cch khc nhau. i tng DataSet thc s cho php ta lu tr m hnh quan h ca database. + ADO ch cho php to client-side cursors, ngc li ADO.NET cho php chn hoc l s dng client-side hoc server-side cursors. Trong ADO.NET, classes thc s iu khin s lm vic ca cc cursors. N cho php pht trin la chn ci tt nht. Nh vy, ty theo ng dng c th ta c th s dng cc m hnh kt ni ng dng vi SQL Server c th. Trong phm vi mn hc ta s s dng m hnh ADO.NET vi cc lp SqlClient v s dng ngn ng lp trnh Visual Basic.NET. 5.2. Cc lp SqlClient trong m hnh ADO.NET
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

216

Danh sch sau cha cc classes ADO.NET m chng s c s dng trong qu trnh xy dng ng dng s dng SQL Server Databases: SqlConnection SqlDataAdapter SqlCommand SqlParameter SqlDataReader Ch : Chng l cc SqlClient c th, tr namespace OleDb c rt nhiu close tng ng. Mi khi ta mun s dng lp classes ny, ta phi add mt tham chiu ti tn min System.Data. n gin, ta c th s dng t kha Imports, v lc ta khng cn phi in y cc thnh phn tn min ca SqlClient trong code, nh on code sau: Imports System.Data.SqlClient Nu ta mun s dng li ca classes ADO.NET, nh l DataSet v DataView khng cn g y tn min, ta cn phi Import the tn min System.Data, nh on code tip theo: Imports System.Data Ta nn quen thuc vi vic import cc tn min khc nhau trong project ca ta. Tuy nhin, c ton din ta s ph chng khi thc hnh cc bi tp. By gi, ta xem xt cc classes chnh tn ti trong namespace System.Data.SqlClient. 5.2.1. Class SqlConnection Class SqlConnection c th coi l tri tim ca cc classes m ta s tho lun trong phn ny, bi v n cung cp mt connection ti SQL Server database. Khi xy dng mt i tng SqlConnection, ta c th chn ch nh mt chui kt ni (connection strings) nh mt tham s. Chui connection cha tt c cc thng tin cn thit m mt connection ti your database.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

217

Nu ta khng ch nh chui kt ni trong khi xy dng, ta c th thit lp n bng vic s dng thuc tnh SqlConnection.ConnectionString. Ta xem xt cc chui connection strings lm vic nh th no? * Cc tham s ca chui kt ni (Connection String Parameters) Phng thc chui connection string c xy dng s ph thc vo data provider g ta ang s dng. Khi truy xut SQL Server, ta thng cung cp Server v Database, c ch dn theo bng sau: Tham s M t Tn ca SQL Server m ta mun truy xut. N thng l tn ca my tnh ang chy SQL Server. Ta c th s dng (local) hoc localhost nu SQL Server trn cng mt my ang chy ng dng. Nu bn s dng cc th hin tn ca SQL Server, th tham s nn cha tn ca my tnh theo sau l u gch cho ngc v tip l th hin tn ca SQL Server. Database L tn ca database m ta mun connect ti.

Server

Ta cng cn mt vi thng tin v authentication v thc hin theo hai cch: bng cch cung cp username v password trong chui kt ni (connection strings) hoc bng cch kt ni ti SQL Server s dng NT account m ng dng ang chy trong . Nu ta mun connect ti server bng vic ch nh username v password, ta cn tnh n cc parameters trong chui kt ni connection, c cho trong bng sau: Tham s User ID M t Username s dng connect ti database. account vi user ID ny phi tn ti trong SQL Server v c php truy cp n database ch nh.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

218

Password

L password ca user ch nh.

Tuy nhin, SQL Server c th c thit lp s dng Windows NT account ca user ngi ang chy chng trnh m connection. Trong trng hp ny, ta khng cn ch nh username v password. Ta ch cn phi ch nh n khi ta ang s dng integrated security (security kt hp - Phng thc ny c gi l security kt hp bi v SQL Server ang c kt hp vi Windows NTs security system v cung cp connection an ton nht bi v cc tham s User ID v Password parameters phi c ch nh trong code). Ta s dng tham s Integrated Security ny, v thit lp l True khi ta mun connect SQL Server ang s dng users NT account hin ti. Tt nhin, vi cc lm vic ny, user ca ng dng phi c cho php s dng SQL Server database. Gi d nh l ang s dng SQL Server Enterprise Manager. hiu chc nng ca cc tham s ny trong chui kt ni ta khi to mt i tng connection, xt on code sau. N s dng lp SqlConnection khi to mt i connection m c s dng ch nh user ID v password trong chui kt ni: Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;" &_ "user id=sa;password=pass2008") Chui kt ni ny s connects ti SQL Server database. Tham s Server ch nh l database nm trn my THUHUONG. Tham s Database ch nh database m ta mun truy cp, trong trng hp ny l database QLDiemSV. Cui cng, cc tham s User ID v Password ch nh User ID v password ca user nh ngha trn database. Ta thy rng, mi mt tham s c gn mt gi tr qua du =, v mi cp parameter - value c phn cch nhau nhau bi du chm phy. Hoc Dim objConnection As SqlConnection = New _ SqlConnection(Server=localhost;Database=pubs; & _ User ID=sa;Password=vbdotnet;)

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

219

Chui kt ni ny s connects ti SQL Server database. Tham s Server ch nh l database nm trn my local. Tham s Database ch nh database m ta mun truy cp l database pubs. Cui cng, cc tham s User ID v Password ch nh User ID v password ca user nh ngha trn database. * M v ng Connection Sau khi khi to i tng connection vi mt chui connection nh trnh by phn trc, ta c th gi cc phng thc ca i tng SqlConnection nh l Open v Close, thm ch open v close mt connection ti database c ch nh trong chui kt ni connection. V d, cho on code sau: ' Open the database connection objConnection.Open() ' ... Use the connection ' Close the connection... objConnection.Close() Ch : Ta c th s dng trnh Wizard thc hin kt ni vi CSDL theo s ch dn ca n. 5.2.2. Class SqlCommand Lp SqlCommand i din cho cc cu lnh SQL thc hin truy vn d liu lu tr. Cc cu lnh l truy vn select, insert, update, hoc delete,.v.v C th l cc chui SQL hoc gi mt stored procedure. V truy vn c thc hin c th cha cc tham s hoc khng cha cc tham s. Kin trc ca lp SqlCommand c mt vi bin s, nhng phng thc n gin nht khi to mt i tng SqlCommand vi khng tham s (parameters). Tip theo, sau khi i tng c khi to, ta c th thit lp cc thuc tnh ta cn thc hin cc thao tc sp ti. on code sau cho php khi to mt i tng SqlCommand: Dim objCommand As SqlCommand = New SqlCommand()

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

220

Khi s dng cc data adapters (b iu hp d liu) v datasets, khng cn gi nhiu cc i tng ca chng. Chng c th ch yu c s dng cho vic thc thi mt cu lnh select, delete, insert, hoc update, m l nhng g ta cp trong chng ny. Ta cng c th s dng cc i tng command vi data reader. Mt data reader l mt la chn khc vi DataSet m n s dng mt vi ti nguyn h thng nhng km mm do. * Thuc tnh Connection Mt vi thuc tnh phi c thit lp trn i tng SqlCommand trc khi ta c th thc hin mt cu truy vn. Thuc tnh u tin trong cc thuc tnh ny l thuc tnh Connection. Thuc tnh ny thit lp ti i tng SqlConnection nh trong on code sau: objCommand.Connection = objConnection Ch : cu lnh c thc hin thnh cng, th connection phi c m thi im thc hin. * Thuc tnh CommandText Thuc tnh tip theo phi c thit lp l thuc tnh CommandText. Thuc tnh ny ch nh chui SQL hoc stored procedure s c thc hin. Hu ht cc databases quy nh t cc cc gi tr ca chui trong cp du cc gi tr ca chui , v d:
Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;" &_ "user id=sa;password=pass2008") Dim objCommand As SqlCommand = New SqlCommand() ' Open the connection, execute the command objConnection.Open() ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "INSERT INTO HOSOSV " & _ "(MaSV, HoDem, TenSV, NgaySinh, MaLop) " & _ "VALUES(SV001,Nguyen Thi,Hoa,12/8/1988,TH05)"

Cu lnh INSERT ch n gin ngha l chn mt hng m vo bng HOSOSV. Trong ct MaSV nhn gi tr SV001, HoDem nhn gi tr Nguyen Thi, TenSV nhn gi tr Hoa, NgaySinh nhn gi tr 12/8/1988 v ct MaLop nhn gi tr TH05.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

221

Vi cch c bn ny cc cu lnh INSERT lm vic trong SQL. Ta c, theo sau INSERT INTO l tn ca bng. Tip l mt danh sch tn cc ct trong cp du ngoc n. Tip theo na l t kha VALUES l danh sch cc gi tr c chn vo ct theo ng th t. Trong v d trn, vi cc gi thit l ta bit cc gi tr chn trong khi thc hin chng trnh, thng l khng c thc trn hu ht cc ng dng. Cng may, ta cng c th to cc cu lnh vi cc tham s v thit lp gi tr cho cc tham s mt cch c lp. Ta s tm hiu cch s dng cc tham s nh th no trong phn Parameters Collection. * Parameters Collection Placeholders, k hiu @, l tin t cc bin trong cc cu lnh SQL; Chng c in vo trc cc tham s. Nh vy, nu ta mun cp nht bng HOSOSV c m t trong v d trc nhng khng bit cc gi tr ti thi im thit k, ta ch cn vit:
Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;" &_ "user id=sa;password=pass2008") Dim objCommand As SqlCommand = New SqlCommand() ' Open the connection, execute the command objConnection.Open() ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "INSERT INTO HOSOSV " & _ "(MaSV, HoDem, TenSV, NgaySinh, MaLop) " & _ "VALUES(@MaSV,@Hodem,@TenSV,@NgaySinh,@MaLop)"

y, thay v cung cp cc gi tr c th, ta cung cp cc placeholders. Placeholders, nh cp, lun xut hin vi k hiu @. Chng khng cn c t trc tn cc trng trong cc bng ca database m chng th hin, nhng thng n gin hn nu ta s dng tn tham s trng vi tn trng d liu, v n thng tt hn cho chnh cc vn bn code ca ta. Tip theo, ta cn to cc tham s m s c s dng truyn gi tr cho cc placeholders khi cu lnh SQL c thc hin. Ta cn phi create v add cc tham s vo Parameters collection ca i tng SqlCommand.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

222

Thut ng parameters ch cc tham s cn thit cho cu lnh SQL hoc stored procedure, khng ch cc tham s c quy nh chuyn chuyn sang cc phng thc ca Visual Basic 2005. Ta c th truy cp vo tp Parameters collection ca i tng SqlCommand bng vic ch nh thuc tnh Parameters. Sau khi truy cp vo tp Parameters collection, ta c th s dng cc thuc tnh v cc phng thc ca n to mt hoc nhiu hn cc tham s trong collection. Cch tt nht add mt tham s ti cu lnh c m t trong v d sau:
Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;" &_ "user id=sa;password=pass2008") Dim objCommand As SqlCommand = New SqlCommand() ' Open the connection, execute the command objConnection.Open() ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "INSERT INTO HOSOSV " & _ "(MaSV, HoDem, TenSV, NgaySinh, MaLop) " & _ "VALUES(@MaSV,@Hodem,@TenSV,@NgaySinh,@MaLop)" ' Add parameters for the placeholders in the SQL in the objCommand.Parameters.AddWithValue("@MaSV", txtMaSV.Text) objCommand.Parameters.AddWithValue("@Hodem", txtHodem.Text) objCommand.Parameters.AddWithValue("@TenSV", txtTenSV.Text) objCommand.Parameters.AddWithValue("@NgaySinh",_ txtNgaySinh.Text).DbType = DbType.Date objCommand.Parameters.AddWithValue("@MaLop", cboMaLop.Text)

Phng thc AddWithValue tha nhn tn ca tham s v i tng ta mun add. Trong trng hp ny, ta s dng thuc tnh Text ca i tng Text box trn cng mt Form. * Phng thc ExecuteNonQuery Cui cng, ta c th thc hin cc cu lnh. lm iu ny, connection cn phi c m. Ta c th gi phng thc ExecuteNonQuery ca i tng SqlCommand. Phng thc ny thc hin cu lnh SQL v l nguyn

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

223

nhn d liu c chn vo database. hon thnh on code, ta phi m connection, thc hin query, v ng connection tr li:
Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;" &_ "user id=sa;password=pass2008") Dim objCommand As SqlCommand = New SqlCommand() ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "INSERT INTO HOSOSV " & _ "(MaSV, HoDem, TenSV, NgaySinh, MaLop) " & _ "VALUES(@MaSV,@Hodem,@TenSV,@NgaySinh,@MaLop)" ' Add parameters for the placeholders in the SQL in the objCommand.Parameters.AddWithValue("@MaSV", txtMaSV.Text) objCommand.Parameters.AddWithValue("@Hodem", txtHodem.Text) objCommand.Parameters.AddWithValue("@TenSV", txtTenSV.Text) objCommand.Parameters.AddWithValue("@NgaySinh",_ txtNgaySinh.Text).DbType = DbType.Date objCommand.Parameters.AddWithValue("@MaLop", cboMaLop.Text) ' Open the connection, execute the command objConnection.Open() ' Execute the SqlCommand object to insert the new data... Try objCommand.ExecuteNonQuery() Catch SqlExceptionErr As SqlException MessageBox.Show(SqlExceptionErr.Message) End Try ' Close the connection... objConnection.Close()

* Phng thc ExecuteReader Tri vi phng thc ExecuteNonQuery, phng thc ExecuteReader ca i tng SqlCommand s thc hin truy vn tr v kt qu trn i tng DataReader. V d liu trn DataReader thng c sang cc iu khin ListBox, ComboBox trn form ng dng.
' Declare local variables and objects... Dim objCommand As SqlCommand = New SqlCommand() Dim objDataReader As SqlDataReader ' Open the connection, execute the command objConnection.Open() ' Set the SqlCommand object properties... objCommand.Connection = objConnection

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

224

objCommand.CommandText = "Select MaLop, TenLop From Lop" ' Execute the SqlCommand object to insert the new data... objDataReader = objCommand.ExecuteReader cboMaLop.Items.Clear() Do While (objDataReader.Read()) cboMaLop.Items.Add(objDataReader.Item(0)) Loop ' Close the connection... objConnection.Close()

5.2.3. Class SqlDataAdapter Lp SqlDataAdapter tng t nh lp OleDbDataAdapter. im khc nhau chnh l OleDbDataAdapter c th truy cp vo bt c data source c supports OLE DB, trong khi SqlDataAdapter ch supports cho SQL Server databases. Ta c th s dng trong cng mt cch nh nhau; ta c th cu hnh SqlDataAdapter s dng wizards, ging nh l cu hnh cho OleDbDataAdapter (c cung ta ang truy xut vo SQL Server data source), ta s trnh by trong v d minh ha c th phn sau. Trong phn ny, ta tm hiu cch cu hnh v s dng SqlDataAdapter trong code, nhng nguyn tc ny cng c th p dng cho OleDbDataAdapter. Data adapters hot ng nh mt cu ni gia data source v cc i tng lu d liu trong b nh, nh l DataSet. truy xut data source, chng s dng cc i tng command, ta xem xt trn. Cc i tng command ny lin quan n cc connections, v vy data adapter ny da vo cc i tng command v connection truy xut v iu khin data source. Thuc tnh SelectCommand ca lp SqlDataAdapter c s dng nm gi mt SqlCommand gi d liu t data source. Sau data adapter y kt qu ca truy vn vo DataSet hoc DataTable. SqlDataAdapter cng c cc thuc tnh UpdateCommand, DeleteCommand, and InsertCommand. Chng cng l cc i tng SqlCommand, c s dng ghi cc thay i vi DataSet hoc DataTable quay tr li data source. Vn ny c th thy phc tp, nhng cc tools thc t rt d s dng. Ta hc cc cu lnh SQL trong chng trc vit

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

225

SelectCommand, v cc tools c gi command builders m ta c th to mt cch t ng cc cu lnh khc da trn chng. Xt thuc tnh SelectCommand v xt xem ta c th to cc cu lnh cho vic updating, deleting, v inserting records nh th no. * Thuc tnh SelectCommand Thuc tnh SelectCommand ca lp SqlDataAdapter c dng y d liu vo t SQL Server database DataSet, nh hnh v Hnh 5.4.

Hnh 5.4. Thuc tnh Select Command Khi ta mun c d liu t kho d liu, u tin ta phi thit lp thuc tnh SelectCommand ca lp SqlDataAdapter. Thuc tnh ny l i tng SqlCommand v n c dng ch nh d liu c select v select d liu nh th no. V vy, thuc tnh SelectCommand cng c cc thuc tnh ca n, v ta cn thit lp chng nh l thit lp cc thuc tnh trn cc cu lnh thng thng. Ta xem xt cc thuc tnh sau ca i tng SqlCommand: Connection: Thit lp i tng SqlConnection truy xut vo data store.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

226

CommandText: Thit lp cc cu lnh SQL hoc tn stored procedure c s dng selectd liu. Trong cc v d trc ca cc i tng SqlCommand, ta s dng trc tip cc cu lnh SQL. Nu ta mun s dng cc stored procedures, ta cn phi s dng thm thuc tnh CommandType, thuc tnh ny thit lp mt gi tr xc nh xem thuc tnh CommandText c bin dch nh th no. Trong chng ny, ta tp trung vo cc cu lnh SQL, nhng cc stored procedures thng cng rt hu dng, c bit l nu chng tn ti trn database. Nu ta mun s dng chng, th thit lp thuc tnh CommandText vi tn ca stored procedure (ch l phi c ng trong cp du ngoc kp tn ca stored procedure hoc chui SQL bi trnh trnh bin dch bin dch chng nh l mt string), v thit lp thuc tnh CommandType thnh CommandType.StoredProcedure. Thit lp SelectCommand vi mt chui SQL Xt xem lm th no, ta c th thit lp cc thuc tnh trn trong code. on code sau cho ta thy cc cch thit lp in hnh khi thc hin chui SQL string:
Declare a SqlDataAdapter object... Dim objDataAdapter As New SqlDataAdapter() Assign a new SqlCommand to the SelectCommand property objDataAdapter.SelectCommand = New SqlCommand() Set the SelectCommand properties... objDataAdapter.SelectCommand.Connection = objConnection objDataAdapter.SelectCommand.CommandText = _ SELECT MaSV, HoDem, TenSV, FROM HOSOSV ORDER BY TenSV, Hodem

u tin trong on code trn khai bo i tng SqlDataAdapter. i tng ny c thuc tnh SelectCommand c thit lp bng SqlCommand; Ta ch cn thit lp cc thuc tnh ca command. Ta thit lp cc thuc tnh bng vic thit lp thuc tnh Connection, i tng connection c hp l th n phi c to trc on code trn. Tip theo, ta thit lp cc thuc tnh ca thuc tnh CommandText bng cc cu lnh SQL SELECT.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

227

Thit lp SelectCommand vi mt Stored Procedure Trong on code tip theo, ta tm hiu cch thit lp cc thuc tnh trn khi s dng thc hin mt stored procedure. Mt stored procedure l mt nhm cc cu lnh SQL v c lu tr trong database di mt tn duy nht v c thc hin nh mt unit. stored procedure trong v d ny (usp_select_DSSV) s dng cng cu lnh SQL ta s dng trong phn trc:
Declare a SqlDataAdapter object... Dim objDataAdapter As New SqlDataAdapter() Assign a new SqlCommand to the SelectCommand property objDataAdapter.SelectCommand = New SqlCommand() Set the SelectCommand properties... objDataAdapter.SelectCommand.Connection = objConnection objDataAdapter.SelectCommand.CommandText = usp_select_DSSV objDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure

Thuc tnh CommandText by gi c ch nh bng tn ca stored procedure m ta mun thc hin thay v chui SQL c ch nh trong v d trc. Cng phi ch n thuc tnh CommandType. Trong v d trc ta khng cn phi chuyn i thuc tnh ny, bi v n c mc nh l CommandType.Text, m ta cn thit lp thc hin cc cu lnh SQL. Trong v d ny, ta phi thit lp gi tr CommandType.StoredProcedure, ch dn rngthuc tnh CommandText cha tn ca stored procedure thc hin. S dng Command Builders to cc Commands khc SelectCommand l tt c nhng g ta cn thit chuyn d liu t database vo DataSet. Sau khi ta cho php cc users thay i i vi DataSet, ta mun ghi nhng thay i tr li database. Ta c th lm iu ny bng vic iu chnh cc i tng cu lnh SQL cho cc cng vic inserting, deleting, and updating. Mt la chn khc, ta c th s dng cc stored procedures. C hai gii php ph thuc vo s am hiu v SQL. Rt may l, c mt cch n gin hn, ta c th s dng command builders to cc cu lnh ny. N ch c mt dng trong cc dng sau:
Declare a SqlDataAdapter object...

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

228

Dim objDataAdapter As New SqlDataAdapter() Assign a new SqlCommand to the SelectCommand property objDataAdapter.SelectCommand = New SqlCommand() Set the SelectCommand properties... objDataAdapter.SelectCommand.Connection = objConnection objDataAdapter.SelectCommand.CommandText = usp_select_DSSV objDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure automatically create update/delete/insert commands Dim objCommandBuilder As SqlCommandBuilder = New _ SqlCommandBuilder(objDataAdapter)

Nh vy, ta c th s dng SqlDataAdapter ghi nhng thay i d liu tr li database. Ta tm hiu k hn v vn ny trong phn v d minh ha. hiu, ta xt cc phng thc m ly d liu t database y vo DataSet:Phng thc Fill . * Phng thc Fill Ta dng phng thc Fill d liu y d liu m i tng SqlDataAdapter s dng SelectCommand ca n ly t kho lu tr d liu vo i tng DataSet. Tuy nhin, trc khi lm iu , ta phi khi to i tng DataSet. s dng i tng DataSet trong project ca ta, ta phi add mt tham chiu ti System.Xml.
Declare a SqlDataAdapter object... Dim objDataAdapter As New SqlDataAdapter() Assign a new SqlCommand to the SelectCommand property objDataAdapter.SelectCommand = New SqlCommand() Set the SelectCommand properties... objDataAdapter.SelectCommand.Connection = objConnection objDataAdapter.SelectCommand.CommandText = usp_select_DSSV objDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure Dim objDataSet as DataSet = New DataSet()

Ta c hai i tng DataSet v SqlDataAdapter, c th in d liu vo DataSet. Phng thc Fill c nhiu phin bn, nhng ta s ch xt tho lun mt phin bn hay c s dng nhiu nht. C php ca phng thc Fill c cho nh sau: SqlDataAdapter.Fill(DataSet, string)

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

229

i s DataSet ch nh mt i tng DataSet hp l m d liu c lu tr trong . i s string gn vi tn m ta mun bng c trong DataSet. Ch rng, mt DataSet c th cha nhiu bng. Ta c th s dng bt c tn no ta mun, nhng thng tt nht l s dng tn ca cc bng ni m d liu trong database n. N gip cho vn bn code ca ta v lm cho code d bo tr. on code sau gi phng thc Fill. Chui authors c ch nh l i s string. N l tn ta mun s dng khi ang thao tc trong cc phin bn nh ca bng ny; n cng l tn ca bng trong data source.
Declare a SqlDataAdapter object... Dim objDataAdapter As New SqlDataAdapter() Create an instance of a new select command object objDataAdapter.SelectCommand = New SqlCommand() Set the SelectCommand properties... objDataAdapter.SelectCommand.Connection = objConnection objDataAdapter.SelectCommand.CommandText = usp_select_DSSV objDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure Dim objDataSet as DataSet = New DataSet() Fill the DataSet object with data... objDataAdapter.Fill(objDataSet, DSSV)

Phng thc Fill s dng thuc tnh SelectCommand.Connection connect ti database. Nu connection c m, data adapter s s dng n thc hin SelectCommand. V nu nh connection ng th data adapter s m n, thc hin SelectCommand, v sau ng tr tr li. By gi ta c d liu trong b nh, v c th bt u thao tc n khng ph thuc vo data source. Ch : Lp DataSet khng c Sql ti v tr bt du tn lp ca n. Bi v DataSet khng nm trong namespace System.Data.SqlClient, n nm trong lp cha namespace System.Data. Cc lp trong tn min ny c lin quan cn bn vi thao cc d liu trong b nh.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

230

Mt ln na, ta c d liu c load vo DataSet, tnh cht quan trng ca data source khng cn na (tr khi ta mun ghi tr li). Ta hy xt hai trong cc lp trong namespace: DataSet v DataView. 5.2.4. Class DataSet Lp DataSet c dng lu tr d liu c ly t mt kho d liu v lu tr d liu trong b nh trn client. i tng DataSet cha mt tp cc tables, relationships, v cc rng buc constraints thch hp vi d liu c t kho d liu. N hot ng nh mt b my database gn nh, cho php ta lu tr tables, edit data, v chy cc truy vn da vo vic s dng i tng DataView. D liu trong DataSet khng c connect t kho d liu, v ta c th lm vic vi d liu c lp vi kho d liu. Ta c th thao tc d liu trong i tng DataSet bng vic adding, updating, v deleting the records. Ta c th p cc thay i ny quay tr li kho d liu gc sau khi s dng data adapter. D liu trong i tng DataSet c duy tr trong Extensible Markup Language (XML), ngha l ta c th save DataSet nh l mt file hoc n gin chuyn n trn network. XML c bo v t ta, nhng ngi pht trin, v chng ta khng bao gi nn edit trc tip XML. Tt c cc thao tc editing XML c thc hin thng qua cc thuc tnh v cc phng thc ca lp DataSet. Nhiu nh pht trin thch s dng XML v la chn thao tc XML biu din trc tip DataSet, nhng iu ny khng cn thit. Ging nh bt c bn document XML no, DataSet c mt schema (mt file cu trc ca d liu trn mt hoc nhiu XML files). Khi ta sinh ra mt kiu dataset dng wizard, XML Schema Definition (XSD) file c add vo Solution Explorer, nh hnh 5.6.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

231

Hnh 5.6. File XML Schema Definition File ny l mt XML schema cho d liu QLDiemSVDataSet cha n. T y, Visual Studio .NET to ra mt lp k tha t DataSet v s dng schema c th ny. Mt lc DataSet cha cc thng tin v tables, relationships, and constraints c lu tr trong DataSet. Thm na, n c bo v t pha ta, v ta khng cn bit XML lm vic vi DataSet. 5.2.5. DataView Lp DataView c s dng tiu biu cho vic sorting, filtering, searching, editing, v navigating d liu t DataSet. Mt DataView l bindable, ngha l n c th b buc vo cc iu khin ging nh cch DataSet b buc vo cc iu khin. Hn na, ta s tm hiu nhiu hn v cch buc d liu trong code trong phn tip theo ca chng. Mt DataSet c th cha mt s cc i tng DataTable; khi ta s dng phng thc Fill ca lp SqlDataAdapter add d liu vo DataSet, nh vy ta thc s ang to mt i tng DataTable bn trong DataSet ny. DataView cung cp view thng dng ca DataTable; ta c th sp xp v lc d liu, nh ta thc hin trn truy vn SQL.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

232

Ta c th to mt DataView t d liu c cha trong DataTable m ang ch cha d liu m ta mun hin th. V d, nu d liu trong DataTable cha tt c cc Sinh vin c sp xp bi Tn v H m, ta c th to mt DataView cha tt c Sinh vin c sp xp bi Tn v sau l H m. Hoc, nu mun, ta c th to mt DataView ch cha mt vi sinh vin cha tn no . Mc d ta c th view d liu trong DataView trong nhiu cch khc nhau t DataTable c bn, n vn l cng d liu. Cc thay i vi DataView nh hng ti DataTable c bn mt cch t ng v cc thay i vi DataTable c bn t ng nh hng bt k i tng DataView m ang hin th DataTable . Kin trc cho lp DataView khi to mt th hin mi ca lp DataView v ly DataTable l mt i s. on code sau khai bo mt i tng DataView v khi to n ang s dng bng HosoSV t DataSet c tn l objDataSet. Ch rng code truy cp vo tp hp Tables ca i tng DataSet, bng vic ch nh thuctnh Tables v tn bng:
Set the DataView object to the DataSet object... Dim objDataView = New DataView(objDataSet.Tables(HosoSV))

* Thuc tnh Sort Khi DataView c khi to v hin th d liu, ta c th thay i view ca d liu . V d, gi s ta mun sp xp d liu khc vi th t trong DataSet. sp xp d liu trong DataView, ta thit lp thuc tnh Sort v ch nh ct hoc cc ct m ta mun sp xp. on code sau s sp xp d liu trong DataView theo Tn v sau theo H m ca danh sch Sinh vin: objDataView.Sort = TenSV, Hodem Ch : Thuc tnh Sort ging nh c php ca mnh ORDER BY trong cu lnh SQL. Nh trong SQL mnh ORDER BY, thao tc sp xp trn DataView thng sp xp theo th t mc nh l tng dn. Nu ta mun thay i theo th t sp xp gim, ta cn phi c ch nh t kha DESC:
objDataView.Sort = TenSV, Hodem DESC

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

233

* Thuc tnh RowFilter Khi khi to DataView, ta c th lc cc dng d liu m chng s cha. N tng t nh ch nh trong mnh WHERE ca cu lnh SQL SELECT; ch nhng hng tha mn iu kin s c gi li trn view. D liu c bn khng b nh hng. Thuc tnh RowFilter ch nh mt iu kin lc m c th p dng c trn DataView. C php ny cng tng t nh mnh SQL WHERE. N cha t nht tn mt ct, theo sau l mt ton t v gi tr. Nu gi tr l string th n phi c bao trong cp du nhy n, v d ta c on code sau:
Set the DataView object to the DataSet object... objDataView = New DataView(objDataSet.Tables(HosoSV)) objDataView.RowFilter = TenSV = Hoa

Nu bn mun ly li cc rng tr cc dng c Tn l =Hoa


Set the DataView object to the DataSet object... objDataView = New DataView(objDataSet.Tables(authors)) objDataView.RowFilter = TenSV <> Hoa

Ta cng c th ch nh iu kin lc phc tp hn nh trong SQL. V d, s dng ton t AND:


objDataView.RowFilter = TenSV <> Hoa AND Hodem LIKE N*

* Phng thc Find Nu ta mun tm kim cho mt hng d liu trong DataView, ta gi phng thc Find. Phng thc Find tm kim d liu trong ct kha sp xp ca DataView. Do , trc khi gi phng thc Find, ta trc ht hy sp xp DataView trn ct cha d liu m ta mun tm kim. Ct trong DataView c sp xp tr thnh ct kha sp xp trong i tng DataView object. V d, gi s ta mun tm kim Sinh vin c TenSV l Anh. Ta cn sp xp d liu trong DataView theo TenSV v thit lp ct ny thnh ct kha sp xp trong DataView, v sau gi phng thc Find, nh on code sau:
Dim intPosition as Integer objDataView.Sort = TenSV intPosition = objDataView.Find(Ann)

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

234

Phng thc Find tm kim v tr v v tr ca bn ghi trong DataView. Trong trng hp ngc li, DataView tr v gi tr null nu khng tm thy. Nu phng thc Find tm thy mt bn khp th n s dng tm kim v tr v v tr ca bn ghi u tin tm thy. Nu ta mun c nhiu hn mt bn ghi trong data store, ta phi lc d liu trong DataView, d liu ca ta s c hin th. Phng thc Find khng phn bit dng ch, ngha l khi tm Sinh vin c tn l Hoa, ta c th nhp l hoa. Phng thc Find tm chnh xc tng cm t, ngha l ta phi nhp ton b cm t . V d, gi s ta mun tm kim Sinh vin c H m l inh Thanh th ta phi nhp y cm .
objDataView.Sort = Hodem intPosition = objDataView.Find(inh Thanh)

Ta thy DataView c th c sp xp trn nhiu hn mt ct ti cng mt thi im. Nu ta mun sp xp nhiu hn mt ct, ta cn cung cp mt mng cc gi tr phng thc Find thay cho ch mt gi tr n. V d, ta mun tm kim inh Thanh Hoa xut hin trong DataView:
Dim intPosition As Integer Dim arrValues(1) As Object objDataView.Sort = Hodem, TenSV Find the author named inh Thanh Hoa. arrValues(0)= inh Thanh arrValues(1) = Hoa intPosition = objDataView.Find(arrValues)

5.3. V d minh ha Mc ch ca phn ny a ra cho sinh vin cc k thut lp trnh qun tr CSDL c bn nh l cp nht d liu, hin th d liu, tm kim d liu, sp xp d liu, xy dng cc bo co thng k, .v.v... Tc gi trnh by chi tit tng bc thit k chng v thng qua sinh vin c th tng hp cc k nng xy dng cho mnh mt ng dng qun l CSDL hon chnh. Khi lp trnh, ta thng dng kt hp gia wizards v coding lp trnh mt cch nhanh chng v d dng. Cc components c th to bng thao tc

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

235

ko th c th c sinh trong code ng nh cc i tng c to trong code. Trong v d minh ha, hiu c bn cht ta tp chung trn code. 5.3.1. CSDL trong v d minh ha Trong phn ny, ta thit k mt CSDL QL_DiemSV rt n gin nhm mc ch minh ha cho cc k nng lp trnh CSDL, gm 4 quan h sau: - Bng H s sinh vin (HOSOSV)

- Bng danh mc Lp (LOP)

- Bng danh mc mn hc (MONHOC)

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

236

- Bng im (DIEM)

- Quan h gia cc bng:

5.3.2. Xy nhp DSSinhVien

dng

Form

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

237

Ta thc hin xy dng from trn thng qua cc i tng sau. 1. To mt Project Windows Application tn l QL_DiemSV. 2. To Form Nhp h s sinh vin (frmNhapHSSV) nh hnh c cc i tng sau: Object Form Label Label Label Label Label Textbox Textbox Textbox Textbox Combo Button Button Button Button Property Name Text Name Text Name Text Name Text Name Text Name Text Name Name Name Name Name Name Text Name Text Name Text Name Text Setting frmNhapHSSV Nhap Ho so sinh vien Label1 NHP DANH SCH SINH VIN lblMaSV M sinh vin lblHodem H m lblTenSV Tn sinh vin lblMaLop M lp txtMaSV txtHodem txtTenSV txtMaLop cboMaLop btnNew New btnAdd Add btnUpdate Update btnDelete Delete
Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Bi ging H qun tr CSDL

238

Textbox Button Button Button Button StatusStrip ToolStripStatusLabel Button

Name Name Text Name Text Name Text Name Text Name Text Name Text Name Text

txtRecordPosition btnMoveFirst |< btnMovePrevious < btnMoveNext > btnMoveLast >| StatusStrip1 StatusStrip1 ToolStripStatusLabel1 ToolStripStatusLabel1 btnClose Close

Sau khi thit k cc i tng trn ta c mt form nh hnh, 3. Import cc tn min cn thit. M code editor v chn on code sau.
' Import Data and SqlClient namespaces... Imports System.Data Imports System.Data.SqlClient

4. Tip theo khai bo cc i tng global trong phm vi ca form ny.


' Import Data and SqlClient namespaces... Imports System.Data Imports System.Data.SqlClient Public Class frmNhapHSSV #Region "Khai bao cac ket noi" Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;user id=sa;password=pass2008") Dim objDataAdapter As New SqlDataAdapter( _ "SELECT MaSV, HoDem, TenSV, NgaySinh, MaLop " & _ "FROM HOSOSV ", objConnection) Dim objDataSet As DataSet Dim objDataView As DataView Dim objCurrencyManager As CurrencyManager #End Region

Ch : Khi khai bo kt ni cn phi m bo ng tn server, user id v password.


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

239

5. Th tc u tin ta s to l th tc FillDataSetAndView. Th tc c th coi l th tc khi to cc i tng.


Private Sub FillDataSetAndView() ' Initialize a new instance of the DataSet object... objDataSet = New DataSet() ' Fill the DataSet object with data... objDataAdapter.Fill(objDataSet, "Hoso") ' Set the DataView object to the DataSet object... objDataView = New DataView(objDataSet.Tables("Hoso")) ' Set our CurrencyManager object to the DataView object... objCurrencyManager = CType(Me.BindingContext(objDataView), CurrencyManager) End Sub

6. Th tc tip theo s thc hin kt ni cc iu khin trn form vi i tng Dataview.


Private Sub BindFields() ' Clear any previous bindings... txtMaSV.DataBindings.Clear() txtHodem.DataBindings.Clear() txtTenSV.DataBindings.Clear() txtNgaySinh.DataBindings.Clear() txtMaLop.DataBindings.Clear() ' Add new bindings to the DataView object... txtMaSV.DataBindings.Add("Text", objDataView, "MaSV") txtHodem.DataBindings.Add("Text", objDataView, "HoDem") txtTenSV.DataBindings.Add("Text", objDataView, "TenSV") txtNgaySinh.DataBindings.Add("Text", objDataView, "Ngaysinh") txtMaLop.DataBindings.Add("Text", objDataView, "MaLop") ' Display a ready status... ToolStripStatusLabel1.Text = "Ready" End Sub

7. Th tc tip theo l s hin th v tr ca bn ghi hin thi trn form.


Private Sub ShowPosition() ' Display the current position and the number of records txtRecordPosition.Text = objCurrencyManager.Position + 1 & _ " / " & objCurrencyManager.Count() End Sub

8. Ta xy dng cc th tc. Ta s gi cc th tc . Double-click Form Designer, chn s kin Load form sau add on code sau.
Private Sub frmNhapHSSV_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Fill the DataSet and bind the fields...

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL


Me.txtMaSV.Enabled = False FillDataSetAndView() BindFields()

240

' Show the current record position... ShowPosition() End Sub

By gi ta s chy th form: Debug\Start Debugging (F5) 9. Tip theo ta s vit code cho cc navigation buttons. thc hin duyt cc bn ghi trn form.
Private Sub btnMoveFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveFirst.Click ' Set the record position to the first record... objCurrencyManager.Position = 0 ' Show the current record position... ShowPosition() End Sub Private Sub btnMovePrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMovePrevious.Click ' Move to the previous record... objCurrencyManager.Position -= 1 ' Show the current record position... ShowPosition() End Sub Private Sub btnMoveNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveNext.Click ' Move to the next record... objCurrencyManager.Position += 1 ' Show the current record position... ShowPosition() End Sub Private Sub btnLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLast.Click ' Set the record position to the last record... objCurrencyManager.Position = objCurrencyManager.Count - 1 ' Show the current record position... ShowPosition() End Sub

10. Thm cc bn ghi. - Trc ht ta a on code sau vo th tc ca nt New.


Private Sub btnNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNew.Click txtMaSV.Text = "" txtHodem.Text = ""

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL


txtTenSV.Text = "" txtNgaySinh.Text = "" txtMaLop.Text = "" Me.txtMaSV.Enabled = True Me.cboMaLop.Visible = True Me.txtMaLop.Visible = False

241

' Declare local variables and objects... Dim objCommand As SqlCommand = New SqlCommand() Dim objDataReader As SqlDataReader ' Open the connection, execute the command objConnection.Open() ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "Select MaLop, TenLop From Lop" ' Execute the SqlCommand object to insert the new data... objDataReader = objCommand.ExecuteReader cboMaLop.Items.Clear() Do While (objDataReader.Read()) cboMaLop.Items.Add(objDataReader.Item(0)) Loop ' Close the connection... objConnection.Close() End Sub

i vi th tc ny, ta s cho cc i tng Text box v rng nhp d liu. Ring Text box txtMaLop s c n i v thay vo l Combo box cboMaLop. Do mi quan h gia hai quan h HOSOSV v LOP, cboMaLop s cha MaLop cc lp c trong danh mc Lop. Trong phn ny, ta c s dng i tng DataReader ca lp SqlDataReader. Khai bo i tng:
' Declare local variables and objects... Dim objCommand As SqlCommand = New SqlCommand() Dim objDataReader As SqlDataReader

Thc hin i tng Command v lu kt qu c vo i tng objDataReader. V truy xut d liu .


' Execute the SqlCommand object to insert the new data... objDataReader = objCommand.ExecuteReader cboMaLop.Items.Clear() Do While (objDataReader.Read()) cboMaLop.Items.Add(objDataReader.Item(0)) Loop

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

242

- Chn d liu vo CSDL. a on code sau vo s kin click ca nt lnh Add.


Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click ' Declare local variables and objects... Dim intPosition As Integer Dim objCommand As SqlCommand = New SqlCommand() ' Save the current record position... intPosition = objCurrencyManager.Position ' Open the connection, execute the command objConnection.Open() ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "INSERT INTO HOSOSV " & _ "(MaSV, HoDem, TenSV, NgaySinh, MaLop) " & _ "VALUES(@MaSV,@Hodem,@TenSV,@NgaySinh,@MaLop)" ' Add parameters for the placeholders in the SQL in the ' CommandText property... objCommand.Parameters.AddWithValue("@MaSV", txtMaSV.Text) objCommand.Parameters.AddWithValue("@Hodem", txtHodem.Text) objCommand.Parameters.AddWithValue("@TenSV", txtTenSV.Text) objCommand.Parameters.AddWithValue("@NgaySinh",_ txtNgaySinh.Text).DbType = DbType.Date objCommand.Parameters.AddWithValue("@MaLop", cboMaLop.Text) ' Execute the SqlCommand object to insert the new data... Try objCommand.ExecuteNonQuery() Catch SqlExceptionErr As SqlException MessageBox.Show(SqlExceptionErr.Message) End Try ' Close the connection... objConnection.Close() ' Fill the dataset and bind the fields... FillDataSetAndView() BindFields() ' Set the record position to the one that you saved... objCurrencyManager.Position = intPosition ' Show the current record position... ShowPosition() ' Display a message that the record was added... ToolStripStatusLabel1.Text = "Record Added" Me.txtMaSV.Enabled = False Me.cboMaLop.Visible = False Me.txtMaLop.Visible = True End Sub

11. Thc hin Update cc bn ghi.


Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click ' Declare local variables and objects... Dim intPosition As Integer Dim objCommand As SqlCommand = New SqlCommand() ' Save the current record position...

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

243

intPosition = objCurrencyManager.Position ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "UPDATE HOSOSV " & _ "SET HoDem = @HoDem, TenSV=@TenSV, NgaySinh=@NgaySinh, MaLop=@MaLop Where MaSV = @MaSV" objCommand.CommandType = CommandType.Text ' Add parameters for the placeholders in the SQL in the ' CommandText property... objCommand.Parameters.AddWithValue("@Hodem", txtHodem.Text) objCommand.Parameters.AddWithValue("@TenSV", txtTenSV.Text) objCommand.Parameters.AddWithValue("@NgaySinh", txtNgaySinh.Text).DbType = DbType.Date objCommand.Parameters.AddWithValue("@MaLop", txtMaLop.Text) objCommand.Parameters.AddWithValue_ ("@MaSV", BindingContext(objDataView).Current("MaSV")) ' Open the connection... objConnection.Open() ' Execute the SqlCommand object to update the data... objCommand.ExecuteNonQuery() ' Close the connection... objConnection.Close() ' Fill the DataSet and bind the fields... FillDataSetAndView() BindFields() ' Set the record position to the one that you saved... objCurrencyManager.Position = intPosition ' Show the current record position... ShowPosition() ' Display a message that the record was updated... ToolStripStatusLabel1.Text = "Record Updated" End Sub

12. Thc hin Delete cc bn ghi.


Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click ' Declare local variables and objects... Dim intPosition As Integer Dim objCommand As SqlCommand = New SqlCommand() ' Save the current record position - 1 for the one to be ' deleted... intPosition = Me.BindingContext(objDataView).Position - 1 ' If the position is less than 0 set it to 0... If intPosition < 0 Then intPosition = 0 End If ' Set the Command object properties... objCommand.Connection = objConnection objCommand.CommandText = "DELETE FROM HOSOSV " & _ "WHERE MaSV = @MaSV;" ' Parameter for the MaSv field... objCommand.Parameters.AddWithValue _ ("@MaSV", BindingContext(objDataView).Current("MaSV"))

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

244

' Open the database connection... objConnection.Open() ' Execute the SqlCommand object to update the data... objCommand.ExecuteNonQuery() ' Close the connection... objConnection.Close() ' Fill the DataSet and bind the fields... FillDataSetAndView() BindFields() ' Set the record position to the one that you saved... Me.BindingContext(objDataView).Position = intPosition ' Show the current record position... ShowPosition() ' Display a message that the record was deleted... ToolStripStatusLabel1.Text = "Record Deleted" End Sub

13. Vit code cho nt Close


Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click Me.Close() End Sub

14. Ta c th bin dch v chy ng dng.

5.3.3. Xy dng Form nhp DSLop

Ta thc hin tng t nh Form trn. Nhng nt Add ta s minh ha cho vic s dng Stored Procedure. - Trong SQL server ta xy dng StoredProcedure nh sau

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

245

- Vit code cho nt Add ny nh sau:


Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click ' Declare local variables and objects... Dim intPosition As Integer Dim objCommand As SqlCommand = New SqlCommand() ' Save the current record position... intPosition = objCurrencyManager.Position ' Open the connection, execute the command objConnection.Open() ' Set the SqlCommand object properties... objCommand.Connection = objConnection objCommand.CommandText = "insert_Lop" objCommand.CommandType = CommandType.StoredProcedure ' Add parameters for the placeholders in the SQL in the ' CommandText property... objCommand.Parameters.AddWithValue("@MaLop", txtMaLop.Text) objCommand.Parameters.AddWithValue("@TenLop", txtTenLop.Text) objCommand.Parameters.AddWithValue("@Khoa", txtKhoa.Text) ' Execute the SqlCommand object to insert the new data...

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL


Try

246

objCommand.ExecuteNonQuery() Catch SqlExceptionErr As SqlException MessageBox.Show(SqlExceptionErr.Message) End Try ' Close the connection... objConnection.Close() ' Fill the dataset and bind the fields... FillDataSetAndView() BindFields() ' Set the record position to the one that you saved... objCurrencyManager.Position = intPosition ' Show the current record position... ShowPosition() ' Display a message that the record was added... ToolStripStatusLabel1.Text = "Record Added" End Sub

5.3.4. Xy dng Form hin th danh sch sinh vin.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

247

Mc ch ca Form thc hin hin th danh sch sinh vin theo tng lp. Ngoi ra ra cho php thc hin cc thao tc: - Cp nht d liu trn Grid. - Sa i d liu trn Grid. - Xa d liu trn Grid. - Sp xp d liu. 1. Xy dng Form nh hnh trn gm cc control sau: Object Form Label Label DataGridView Button Button Button Button Button Button ComboBox ComboBox Property Name Text Name Text Name Text Name Name Text Name Text Name Text Name Text Name Text Name Text Name Name Items Setting frmDanhSach Danh sch sinh vin lblDSL Danh sch lp lblDSSV DANH SCH SINH VIN dgDanhsach btnClose Close btnInsert Insert btnUpdate Update btnDelete Delete btnUndo Undo btnSort Sp xp cboMaLop cboSX Tn; H tn; M sinh vin
Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Bi ging H qun tr CSDL

248

2. Import cc tn min cn thit. M code editor v chn on code sau.


' Import Data and SqlClient namespaces... Imports System.Data Imports System.Data.SqlClient

3. Tip theo khai bo cc i tng global trong phm vi ca form ny.


#Region "Khai bao cac ket noi" Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;user id=sa;password=12102006") Dim objDataAdapter As New SqlDataAdapter() Dim objDataSet As DataSet Dim objDataView As DataView #End Region

Ch : Khi khai bo kt ni cn phi m bo ng tn server, user id v password. 4. Th tc u tin ta s to l th tc FillDataSetAndView. Th tc c th coi l th tc khi to cc i tng.
Private Sub FillDataSetAndView() ' Initialize a new instance of the DataSet object... objDataSet = New DataSet() objDataAdapter.SelectCommand = New SqlCommand() objDataAdapter.SelectCommand.Connection = objConnection objDataAdapter.SelectCommand.CommandText = _ "SELECT MaSV, HoDem, TenSV, NgaySinh, MaLop FROM HOSOSV WHERE MaLop= '" & cboMaLop.SelectedItem(0) & "'" objDataAdapter.SelectCommand.CommandType = CommandType.Text ' Open the database connection... objConnection.Open() ' Fill the DataSet object with data... objDataAdapter.Fill(objDataSet, "HosoSV") ' Close the database connection... objConnection.Close() ' Set the DataView object to the DataSet object... objDataView = New DataView(objDataSet.Tables("HosoSV")) End Sub

5. Th tc tip theo l th tc thc hin trang tr DataGridView

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL


Private Sub Grid()

249

' * trang tri Datagrid ' Declare and set the currency header alignment property... Dim objAlignRightCellStyle As New DataGridViewCellStyle objAlignRightCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight ' Declare and set the alternating rows style... Dim objAlternatingCellStyle As New DataGridViewCellStyle() objAlternatingCellStyle.BackColor = Color.WhiteSmoke dgDanhSach.AlternatingRowsDefaultCellStyle = objAlternatingCellStyle ' Change column names and styles dgDanhSach.Columns(0).HeaderText dgDanhSach.Columns(1).HeaderText dgDanhSach.Columns(2).HeaderText dgDanhSach.Columns(3).HeaderText dgDanhSach.Columns(4).HeaderText using the column index = "M sinh vin" = "H m" = "Tn" = "Ngy sinh" = "M lp"

' Clean up objAlternatingCellStyle = Nothing objAlignRightCellStyle = Nothing End Sub

6. Vit code cho th tc Load form.


Private Sub frmDanhSach_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' Dien d lieu vo cboMaLop Dim objDA_Lop As New SqlDataAdapter() Dim objDS_Lop As New DataSet() objDA_Lop.SelectCommand = New SqlCommand() objDA_Lop.SelectCommand.Connection = objConnection objDA_Lop.SelectCommand.CommandText = "SELECT MaLop, TenLop FROM Lop" objDA_Lop.SelectCommand.CommandType = CommandType.Text objConnection.Open() ' Fill the DataSet object with data... objDA_Lop.Fill(objDS_Lop, "DMLop") ' Close the database connection... objConnection.Close() Me.cboMaLop.DataSource = objDS_Lop.Tables("DMLop") Me.cboMaLop.DisplayMember = "TenLop" Me.cboMaLop.ValueMember = "MaLop" 'Khi to d liu FillDataSetAndView() Me.dgDanhSach.AutoGenerateColumns = True Me.dgDanhSach.DataSource = objDataView Grid() End Sub

7. Vit code cho nt lnh Close thc hin ng form.


Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

250

Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click me.Close End Sub

8. Vit code cho nt lnh Update thc hin ghi li cc thay i d liu vc s d liu.
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click ' automatically create update/delete/insert commands Dim objCommandBuilder As SqlCommandBuilder = New SqlCommandBuilder(objDataAdapter) objDataAdapter.UpdateCommand = objCommandBuilder.GetUpdateCommand ' Open the connection, execute the command objConnection.Open() objDataAdapter.Update(objDataSet, "HosoSV") objDataSet.Tables("HosoSV").AcceptChanges() objConnection.Close() End Sub

9.Vit code cho nt lnh Insert thc hin chn d liu thc s vo c s d liu.
Private Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInsert.Click ' automatically create update/delete/insert commands Dim objCommandBuilder As SqlCommandBuilder = New SqlCommandBuilder(objDataAdapter) objDataAdapter.InsertCommand = objCommandBuilder.GetInsertCommand ' Open the connection, execute the command objConnection.Open() objDataAdapter.Update(objDataSet, "HosoSV") objDataSet.Tables("HosoSV").AcceptChanges() objConnection.Close() End Sub

10.Vit code cho nt lnh Delete thc hin xa thc s d liu CSDL, sau khi thc hin xa tm trn Grid.
Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click ' automatically create update/delete/insert commands Dim objCommandBuilder As SqlCommandBuilder = New SqlCommandBuilder(objDataAdapter) objDataAdapter.DeleteCommand = objCommandBuilder.GetDeleteCommand ' Open the connection, execute the command objConnection.Open()

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

251

objDataAdapter.Update(objDataSet, "HosoSV") objDataSet.Tables("HosoSV").AcceptChanges() objConnection.Close() Me.Refresh() End Sub

11.Vit code cho nt lnh Undo thc hin Undo li cc thao tc tm trn Grid m cha thi hnh thc s i vi CSDL.
Private Sub btnUndo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUndo.Click Me.Refresh() FillDataSetAndView() Me.dgDanhSach.AutoGenerateColumns = True Me.dgDanhSach.DataSource = objDataView Grid() End Sub

12.Vit code cho nt lnh Sp xp thc hin thc hin sp xp cc bn ghi trn Grid theo 3 tiu ch. - Sp xo theo m sinh vin - Sp xp theo tn sinh vin - Sp xp theo H v tn sinh vin.
Private Sub btnSort_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSort.Click ' Sort property of the DataView object... FillDataSetAndView() Select Case cboSX.SelectedIndex Case 0 'Ten objDataView.Sort = "TenSV" Case 1 'Hoten objDataView.Sort = "TenSV, Hodem" Case 2 'Ma SV objDataView.Sort = "MaSV" End Select Me.dgDanhSach.AutoGenerateColumns = True Me.dgDanhSach.DataSource = objDataView Grid() End Sub

13.Vit code cho s kin chn d liu trm cboMaLop. on code ny nhm mc ch ng b ha d liu trn Form.
Private Sub cboMaLop_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboMaLop.SelectedIndexChanged

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

252

FillDataSetAndView() ' Me.dgDanhSach.AutoGenerateColumns = True Me.dgDanhSach.DataSource = objDataSet Me.dgDanhSach.DataMember = "HosoSV" Grid() End Sub

14. Ta c th thc hin cho chy v th nghim form trn. 5.3.5. Xy dng bo co dng Report. 5.3.5.1. To file Report.rdlc 1. Right - Click trn Project QL_DiemSV/Add/New Item/ chn template Report. Xut hin ca s thit k Report. 2. T menu Data chn Add New Data source to ngun d liu mi s th hin trn report hoc chn Show data sources nu tn ti trc . y ta chn Add New Data source. Cc ca s Wizard s ch dn ta thc hin. Ca s 1. Chn Database/ Nt Next.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

253

Ca s 2: Click nt New Connection

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

254

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

255

Ca s 3: Ca s Add new Connection. Ta thc hin in cc tham s nh hnh.

Sau khi chn OK, n s quay tr li ca s 2.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

256

Ca s 4. Chn d liu s th hin trn Report v t tn cho Dataset.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

257

Chn view Danh sach Click nt Finish. 3. Sau khi c ngun d liu, trong ca s thit k Report ta s thit k d liu s hin th trn Report. Nh hnh, gm cc i tng sau: Object Textbox Textbox Textbox Textbox Table Textbox Textbox Textbox Textbox Textbox Textbox Textbox Textbox Textbox Property Name Value Name Value Name Value Name Value Name Datasetname Name Value Name Value Name Value Name Value Name Value Name Value Name Value Name Value Name Value textbox1
HC VIN K THUT QUN S

Setting

textbox2
H HC VIN DN S

Textbox3
------o0o-----

Textbox4 ="DANH SCH SINH VIN" Table1 DatasetDSSv Textbox5


="Tn lp: " & Fields!TenLop.Value

Textbox6
STT

Textbox7
M sinh vin

Textbox8
H tn

Textbox9
Ngy sinh

Textbox10
=RowNumber("table1_Group2")

Textbox11
=Fields!MaSV.Value

Textbox12
=Fields!Hoten.Value

Textbox13
=Fields!Ngaysinh.Value

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

258

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

259

* Chn group vo bng. - Trong ca s thit k Right-click vo Table ti dng ta mun chn Group v chn Insert Group.

- Trn tab General ta in cc tham s: + Name: Tn ca group + Group on: Chn biu thc m da vo d liu gom nhm. + Document map label: nh hoc chn biu thc c s dng lm nhn nh x. + Parent group: Nu group ny l nhm phn cp ngc (phn cp quy) ta s nh hoc chn biu thc lm nhm cha (recursive group parent). + Option chn Page break at start hoc Page break at end: thay th cho mt page break ti mt v tr bt u hoc kt thc mt th hin ca nhm.
Bin son: Chu Th Hng B mn: Cc h thng thng tin Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

260

+ Include group header hoc Include group footer: Cho hin thi hay khng hin th Header v Footer ca nhm trn Table. + Repeat group header hoc Repeat group footer: lp li group header hoc footer trn mi trang m trong bng xut hin. - Trn tab Fillters: Chn hoc nh biu thc dng lc d liu trn nhm. - Trn tab Sorting: Chn hoc nh biu thc dng sp xp d liu trn nhm. - Trn tab Visibility: chn Visible. - Trn tab Data Output: Chn Yes. Trong v d ta chn hai Group: table1_GroupTenLop v table1_Group2

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

261

5.3.5.2. Hin th d liu.

kt Report vo form, ta xy dng form hin th. t mt iu khin Report Viewer. Trn Report Viewer Tasks chn cc mc sau: - Choose report: Chn report ta va thit k (report.rdlc) - Dock in parent container. Chn. 5.2.5.3. S dng tham s trong Report. a) To tham s Trong ca s thit k Report, thit lp tham s ta thc hin nh sau: T menu Report\Report Paramaters Add cc tham s cho Report.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

262

- Chn nt Add to thm mt tham s mi gm cc thng tin: Name: Tn tham s Data type: Kiu d liu ca tham s

Prompt: in on text s xut hin sau parameter text box khi ngi s dng thc hin chy report. Allow null value: Chn khi cho php tham s nhn gi tr null. Allow blank value: Chn khi cho php thma s nhn gi tr blank. Available values: a ra mt danh sch cc gi tr sn c m ngi s dng c th la chn.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

263

Lable: Cha nhn s c s dng hin th cho ngi s dng. Value: L gi tr s c s dng chuyn qua Report sever cho tham s. Default values: Gi tr mc nh cho tham s. - Chn nt Remove xa tham s chn. Sau khi to tham s, ta c th s dng tham s trong khi thit k Report. Trong v d ta ny ta xy dng mt report nh trn, ngoi ra add thm tham s prmTenLop v lc d liu theo tham s.

b)Truyn gi tr cho tham s: truyn gi tr cho tham s ta s dng phng thc SetParameters ca lp Report trong tn min Microsoft.Reporting.WinForms. C th ta s dng nh sau:
Gn gi tr cho tham s

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

264

Dim p As New ReportParameter("prmTenLop", Me.cboMaLop.SelectedItem(1).ToString) Truyn gi tr vo report Me.rvwDSReport.LocalReport.SetParameters(New ReportParameter() {p})

Gi s ta c form hin th Report nh sau:

C cc i tng sau: Object Form Label ComboBox Report Viewer Property Name Text Name Text Name Name Choose report Setting frmReportCode frmReportCode lblDSL Danh sch ca lp cboMaLop rvwDSL Chn Report to nh trn
Khoa Cng ngh Thng tin

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Bi ging H qun tr CSDL

265

1. Import cc tn min cn thit.


' Import Data and SqlClient namespaces... Imports System.Data Imports System.Data.SqlClient Imports Microsoft.Reporting.WinForms

2. Khai bo cc kt ni
Dim objConnection As New SqlConnection _ ("server=THUHUONG;database=QLDiemSV;user id=sa;password=12102006")

3. Code so s kin load form.


Private Sub frmReportCode_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Dien d lieu vo cboLop Dim objDA_Lop As New SqlDataAdapter() Dim objDS_Lop As New DataSet() objDA_Lop.SelectCommand = New SqlCommand() objDA_Lop.SelectCommand.Connection = objConnection objDA_Lop.SelectCommand.CommandText = "SELECT MaLop, TenLop FROM Lop" objDA_Lop.SelectCommand.CommandType = CommandType.Text objConnection.Open() ' Fill the DataSet object with data... objDA_Lop.Fill(objDS_Lop, "DMLop") ' Close the database connection... objConnection.Close() Me.cboMaLop.DataSource = objDS_Lop.Tables("DMLop") Me.cboMaLop.DisplayMember = "TenLop" Me.cboMaLop.ValueMember = "MaLop" ' Set tham so cho Report Dim p As New ReportParameter("prmTenLop", Me.cboMaLop.SelectedItem(1).ToString) Me.rvwDSReport.LocalReport.SetParameters(New ReportParameter() {p}) 'This line of code loads data into the 'QLDiemSVDataSet.DanhSach' Me.objTableAdapterDSSV.Fill(Me.objDataSetDSSV.DanhSach) Me.rvwDSReport.RefreshReport() End Sub

4. ng b ha d liu trn form.


Private Sub cboMaLop_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboMaLop.SelectedIndexChanged Dim p As New ReportParameter("prmTenLop", Me.cboMaLop.SelectedItem(1).ToString) Me.rvwDSReport.LocalReport.SetParameters(New ReportParameter() {p}) Me.rvwDSReport.RefreshReport() End Sub

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

266

5.3.6. Xy dng report dng Crystal Report. Trong phn ny hng dn xy dng Report bng Crystal report mt cch n gin nht, s dng Wizard. Trong khi thit k ta nn dng wizard thit k s b, sau chuyn vo ca s thit k thit k chi tit. Cc bc thit k report. 1. Right Click trn Project QL_DiemSV/Add/New Item/ chn template Crystal Report. in tn file ca Crystal Report. Xut hin ca s sau: Ca s 1.

2. Chn Using the Repor Wizart v Standard OK.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

267

Ca s 2.

Chn OLE DB (ADO) Xut hin ca s 3.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

268

Ca s 3:

Chn Microsoft OLE DB Provider for SQL Server. Next.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

269

Ca s 4:

Chn server, User, password v Database. Finish. quay li ca s 2. Chn d liu s c hin th trn report.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

270

Ca s 2: Chn ngun d liu cho Report.

Chn Next tip tc theo s ch dn ca wizard.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

271

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

272

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

273

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

274

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin

Bi ging H qun tr CSDL

275

Sau khi xy dng c file *.rpt. Ta xy dng form hin th report trn. Thit k form nh hnh gm mt i tng Crystal Report Viewer. Trn Crystal Report Viewer tasks thc hin cc mc: - Choose a crystal report: Chn Report va to trn. - Dock in parent container: Chn.

Bin son: Chu Th Hng

B mn: Cc h thng thng tin

Khoa Cng ngh Thng tin