This preview has intentionally blurred parts. Sign up to view the full document

View Full Document

Unformatted Document Excerpt

SQL HC SERVER 2000 1 MC LC Overview of SQL Server 2000 ........................................................................................... 2 Transact SQL ...................................................................................................................... 7 Backup And Restore SQL Server ..................................................................................... 24 Stored Procedure and Advanced T-SQL........................................................................... 41 Triggers And Views.......................................................................................................... 51 http://ebooks.vdcmedia.com HC SQL SERVER 2000 2 Overview of SQL Server 2000 c v hiu bi vit ny bn phi c kin thc cn bn v SQL v Access Database Gii Thiu SQL Server 2000 SQL Server 2000 l mt h thng qun l c s d liu (Relational Database Management System (RDBMS) ) s dng Transact-SQL trao i d liu gia Client computer v SQL Server computer. Mt RDBMS bao gm databases, database engine v cc ng dng dng qun l d liu v cc b phn khc nhau trong RDBMS. SQL Server 2000 c ti u c th chy trn mi trng c s d liu rt ln (Very Large Database Environment) ln n Tera-Byte v c th phc v cng lc cho hng ngn user. SQL Server 2000 c th kt hp "n " vi cc server khc nh Microsoft Internet Information Server (IIS), E-Commerce Server, Proxy Server.... SQL Server c 7 editions: Enterprise : Cha y cc c trng ca SQL Server v c th chy tt trn h thng ln n 32 CPUs v 64 GB RAM. Thm vo n c cc dch v gip cho vic phn tch d liu rt hiu qu (Analysis Services) Standard : Rt thch hp cho cc cng ty va v nh v gi thnh r hn nhiu so vi Enterprise Edition, nhng li b gii hn mt s chc nng cao cp (advanced features) khc, edition ny c th chy tt trn h thng ln n 4 CPU v 2 GB RAM. Personal: c ti u ha chy trn PC nn c th ci t trn hu ht cc phin bn windows k c Windows 98. Developer : C y cc tnh nng ca Enterprise Edition nhng c ch to c bit nh gii hn s lng ngi kt ni vo Server cng mt lc.... y l edition m cc bn mun hc SQL Server cn c. Chng ta s dng edition ny trong sut kha hc. Edition ny c th ci trn Windows 2000 Professional hay Win NT Workstation. Desktop Engine (MSDE): y ch l mt engine chy trn desktop v khng c user interface (giao din). Thch hp cho vic trin khai ng dng my client. Kch thc database b gii hn khong 2 GB. http://ebooks.vdcmedia.com HC SQL SERVER 2000 Win CE : Dng cho cc ng dng chy trn Windows CE 3 Trial: C cc tnh nng ca Enterprise Edition, download free, nhng gii hn thi gian s dng. Ci t SQL Server 2000 (Installation) Cc bn cn c Developer Edition v t nht l 64 MB RAM, 500 MB hard disk c th install SQL Server. Bn c th install trn Windows Server hay Windows XP Professional, Windows 2000 Professional hay NT Workstation nhng khng th install trn Win 98 family. V mt trong nhng c im ca cc sn phm Microsoft l d install nn chng ti khng trnh by chi tit v cch install hay cc bc install m ch trnh by cc im cn lu khi install m thi. Nu cc bn gp tr ngi trong vic install th c th a ln forum hi thm. Khi install bn cn lu cc im sau: mn hnh th hai bn chn Install Database Server. Sau khi install xong SQL Server bn c th install thm Analysis Service nu bn thch. mn hnh Installation Definition bn chn Server and Client Tools. Sau bn nn chn kiu Custom v chn tt c cc b phn ca SQL Server. Ngoi ra nn chn cc gi tr mc nh (default) mn hnh Authentication Mode nh chn Mixed Mode . Lu v SQL Server c th dng chung ch bo mt (security) vi Win NT v cng c th dng ch bo mt ring ca n. Trong Production Server ngi ta thng dng Windows Authetication v an ton cao hn v d dng cho ngi qun l mng v c cho ngi s dng. Ngha l mt khi bn c chp nhn (authenticated) kt ni vo domain th bn c quyn truy cp d liu (access data) trong SQL Server. Tuy nhin ta nn chn Mixed Mode d dng cho vic hc tp. Sau khi install bn s thy mt icon nm gc phi bn di mn hnh, y chnh l Service Manager. Bn c th Start, Stop cc SQL Server services d dng bng cch double-click vo icon ny. Mt cht kin thc v cc Version ca SQL Server SQL Server ca Microsoft c th trng chp nhn rng ri k t version 6.5. Sau Microsoft ci tin v hu nh vit li mt engine mi cho SQL Server 7.0. Cho nn c th ni t version 6.5 ln version 7.0 l mt bc nhy vt. C mt s c tnh ca SQL Server 7.0 khng tng thch vi version 6.5. Trong khi http://ebooks.vdcmedia.com HC SQL SERVER 2000 4 t Version 7.0 ln version 8.0 (SQL Server 2000) th nhng ci tin ch yu l m rng cc tnh nng v web v lm cho SQL Server 2000 ng tin cy hn. Mt im c bit ng lu version 2000 l Multiple-Instance. Ni cho d hiu l bn c th install version 2000 chung vi cc version trc m khng cn phi uninstall chng. Ngha l bn c th chy song song version 6.5 hoc 7.0 vi version 2000 trn cng mt my (iu ny khng th xy ra vi cc version trc y). Khi version c trn my bn l Default Instance cn version 2000 mi va install s l Named Instance. Cc thnh phn quan trng trong SQL Server 2000 SQL Server 2000 c cu to bi nhiu thnh phn nh Relational Database Engine, Analysis Service v English Query.... Cc thnh phn ny khi phi hp vi nhau to thnh mt gii php hon chnh gip cho vic lu tr v phn tch d liu mt cch d dng. Relational Database Engine - Ci li ca SQL Server: y l mt engine c kh nng cha data cc quy m khc nhau di dng table v support tt c cc kiu kt ni (data connection) thng dng ca Microsoft nh ActiveX Data Objects (ADO), OLE DB, and Open Database Connectivity (ODBC). Ngoi ra n cn c kh nng t iu chnh (tune up) v d http://ebooks.vdcmedia.com HC SQL SERVER 2000 5 nh s dng thm cc ti nguyn (resource) ca my khi cn v tr li ti nguyn cho h iu hnh khi mt user log off. Replication - C ch to bn sao (Replica): Gi s bn c mt database dng cha d liu c cc ng dng thng xuyn cp nht. Mt ngy p tri bn mun c mt ci database ging y ht nh th trn mt server khc chy bo co (report database) (cch lm ny thng dng trnh nh hng n performance ca server chnh). Vn l report server ca bn cng cn phi c cp nht thng xuyn m bo tnh chnh xc ca cc bo co. Bn khng th dng c ch back up and restore trong trng hp ny. Th th bn phi lm sao? Lc c ch replication ca SQL Server s c s dng bo m cho d liu 2 database c ng b (synchronized). Replication s c bn k trong bi 12 Data Transformation Service (DTS) - Mt dch v chuyn dch data v cng hiu qu Nu bn lm vic trong mt cng ty ln trong data c cha trong nhiu ni khc nhau v cc dng khc nhau c th nh cha trong Oracle, DB2 (ca IBM), SQL Server, Microsoft Access....Bn chc chn s c nhu cu di chuyn data gia cc server ny (migrate hay transfer) v khng ch di chuyn bn cn mun nh dng (format) n trc khi lu vo database khc, khi bn s thy DTS gip bn gii quyt cng vic trn d dng nh th no. DTS s c bn k trong bi 8. Analysis Service - Mt dch v phn tch d liu rt hay ca Microsoft D liu (Data) cha trong database s chng c ngha g nhiu nu nh bn khng th ly c nhng thng tin (Information) b ch t . Do Microsoft cung cp cho bn mt cng c rt mnh gip cho vic phn tch d liu tr nn d dng v hiu qu bng cch dng khi nim hnh khi nhiu chiu (multidimension cubes) v k thut "o m d liu" (data mining) s c chng ti gii thiu trong bi 13. English Query - Mt dch v m ngi Vit Nam chc l t mun dng :-) (?) y l mt dch v gip cho vic query data bng ting Anh "trn" (plain English). Meta Data Service: Dch v ny gip cho vic cha ng v "xo nu" Meta data d dng hn. Th th Meta Data l ci g vy? Meta data l nhng thng tin m t v cu trc ca data trong database nh data thuc loi no String hay Integer..., mt ct no http://ebooks.vdcmedia.com HC SQL SERVER 2000 6 c phi l Primary key hay khng....Bi v nhng thng tin ny cng c cha trong database nn cng l mt dng data nhng phn bit vi data "chnh thng" ngi ta gi n l Meta Data. Phn ny chc l bn phi xem thm trong mt thnh phn khc ca SQL Server sp gii thiu sau y l SQL Server Books Online v khng c bi no trong lot bi ny ni r v dch v ny c. SQL Server Books Online - Quyn Kinh Thnh khng th thiu: Cho d bn c c cc sch khc nhau dy v SQL server th bn cng s thy books online ny rt hu dng v khng th thiu c( cho nn Microsoft mi ho phng nh km theo SQL Server). SQL Server Tools - y l mt b ngh ca ngi qun tr c s d liu (DBA ) i ch nu k chi tit ra th hi nhiu y cho nn bn cn c thm trong books online. y ngi vit ch k ra mt vi cng c thng dng m thi. u tin phi k n Enterprise Manager. y l mt cng c cho ta thy ton cnh h thng c s d liu mt cch rt trc quan. N rt hu ch c bit cho ngi mi hc v khng thng tho lm v SQL. K n l Query Analyzer. i vi mt DBA gii th hu nh ch cn cng c ny l c th qun l c mt h thng database m khng cn n nhng th khc. y l mt mi trng lm vic kh tt v ta c th nh bt k cu lnh SQL no v chy ngay lp tc c bit l n gip cho ta debug my ci stored procedure d dng. Cng c th ba cn phi k n l SQL Profiler. N c kh nng "chp" (capture) tt c cc s kin hay hot ng din ra trn mt SQL server v lu li di dng text file rt hu dng trong vic kim sot hot ng ca SQL Server. Ngoi mt s cng c trc quan nh trn chng ta cng thng hay dng osql v bcp (bulk copy) trong command prompt. Tm li trong bi ny chng ta do qua mt vng tm hiu v SQL Server. Trong bi sau chng ta cng s tip tc do chi thm mt cht vi TransactSQL trc khi i su vo cc ti khc. http://ebooks.vdcmedia.com HC SQL SERVER 2000 7 Transact SQL Gii Thiu S Lc V Transact SQL (T-SQL) Transact-SQL l ngn ng SQL m rng da trn SQL chun ca ISO (International Organization for Standardization) v ANSI (American National Standards Institute) c s dng trong SQL Server khc vi P-SQL (ProceduralSQL) dng trong Oracle. Trong bi ny chng ta s tm hiu s qua v T-SQL. Chng c chia lm 3 nhm: Data Definition Language (DDL): y l nhng lnh dng qun l cc thuc tnh ca mt database nh nh ngha cc hng hoc ct ca mt table, hay v tr data file ca mt database...thng c dng Create object_Name Alter object_Name Drop object_Name Trong object_Name c th l mt table, view, stored procedure, indexes... V d: Lnh Create sau s to ra mt CompanyID,CompanyName,Contact table tn Importers vi 3 ct USE Northwind CREATE TABLE Importers( CompanyID int NOT NULL, CompanyName varchar(40) NOT NULL, Contact varchar(40) NOT NULL ) Lnh Alter sau y cho php ta thay i nh ngha ca mt table nh thm(hay bt) mt ct hay mt Constraint...Trong v d ny ta s thm ct ContactTitle vo table Importers USE Northwind http://ebooks.vdcmedia.com HC SQL SERVER 2000 8 ALTER TABLE Importers ADD ContactTitle varchar(20) NULL Lnh Drop sau y s hon ton xa table khi database ngha l c nh ngha ca table v data bn trong table u bin mt (khc vi lnh Delete ch xa data nhng table vn tn ti). USE Northwind DROP TABLE Importers Data Control Language (DCL): y l nhng lnh qun l cc quyn truy cp ln tng object (table, view, stored procedure...). Thng c dng sau: Grant Revoke Deny V d: Lnh sau s cho php user trong Public Role c quyn Select i vi table Customer trong database Northwind (Role l mt khi nim ging nh Windows Group s c bn k trong phn Security) USE Northwind GRANT SELECT ON Customers TO PUBLIC Lnh sau s t chi quyn Select i vi table Customer trong database Northwind ca cc user trong Public Role USE Northwind DENY SELECT ON Customers TO PUBLIC Lnh sau s xa b tc dng ca cc quyn c cho php hay t chi trc USE Northwind REVOKE SELECT ON Customers TO PUBLIC http://ebooks.vdcmedia.com HC SQL SERVER 2000 9 Data Manipulation Language (DML): y l nhng lnh ph bin dng x l data nh Select, Update, Insert, Delete V d: Select USE Northwind SELECT CustomerID, CompanyName, ContactName FROM Customers WHERE (CustomerID = 'alfki' OR CustomerID = 'anatr') ORDER BY ContactName Insert USE Northwind INSERT INTO Territories VALUES (98101, 'Seattle', 2) Update USE Northwind UPDATE Territories SET TerritoryDescription = 'Downtown Seattle' WHERE TerritoryID = 98101 Delete USE Northwind DELETE FROM Territories WHERE TerritoryID = 98101 V phn ny kh cn bn nn chng ti thit ngh khng cn gii thch nhiu. Ch trong lnh Delete bn c th c ch From hay khng u c. Nhng m chng ta s chy th cc v d trn u? chy cc cu lnh th d trn bn cn s dng v lm quen vi Query Analyser http://ebooks.vdcmedia.com HC SQL SERVER 2000 10 C Php Ca T-SQL: Phn ny chng ta s bn v cc thnh phn to nn c php ca T-SQL Identifiers y chnh l tn ca cc database object. N dng xc nh mt object. (Ch khi ni n Object trong SQL Server l chng ta mun cp n table, view, stored procedure, index.....V hu nh mi th trong SQL Server u c thit k theo kiu hng i tng (object-oriented)). Trong v d sau TableX, KeyCol, Description l nhng identifiers CREATE TABLE TableX (KeyCol INT PRIMARY KEY, Description NVARCHAR(80)) C hai loi Identifiers mt loi thng thng (Regular Identifier) v mt loi gi l Delimited Identifier, loi ny cn c du "" hay du [] ngn cch. Loi Delimited c dng i vi cc ch trng vi t kha ca SQL Server (reserved keyword) hay cc ch c khong trng. http://ebooks.vdcmedia.com HC SQL SERVER 2000 11 V d: SELECT * FROM [My Table] WHERE [Order] = 10 Trong v d trn ch Order trng vi keyword Order nn cn t trong du ngoc vung []. Variables (Bin) Bin trong T-SQL cng c chc nng tng t nh trong cc ngn ng lp trnh khc ngha l cn khai bo trc loi d liu trc khi s dng. Bin c bt u bng du @ (i vi cc global variable th c hai du @@) V d: USE Northwind DECLARE @EmpIDVar INT SET @EmpIDVar = 3 SELECT * FROM Employees WHERE EmployeeID = @EmpIDVar + 1 Functions (Hm) C 2 loi hm mt loi l built-in v mt loi user-defined Cc hm Built-In c chia lm 3 nhm: Rowset Functions : Loi ny thng tr v mt object v c i x nh mt table. V d nh hm OPENQUERY s tr v mt recordset v c th ng v tr ca mt table trong cu lnh Select. Aggregate Functions : Loi ny lm vic trn mt s gi tr v tr v mt gi tr n hay l cc gi tr tng. V d nh hm AVG s tr v gi tr trung bnh ca mt ct. Scalar Functions : Loi ny lm vic trn mt gi tr n v tr v mt gi tr n. Trong loi ny li chia lm nhiu loi nh nh cc hm v ton hc, v thi gian, x l kiu d liu String....V d nh hm MONTH('2002-09-30') s tr v thng 9. Cc hm User-Defined (c to ra bi cu lnh CREATE FUNCTION v phn body thng c gi trong cp lnh BEGIN...END) cng c chia lm cc nhm nh sau: Scalar Functions : Loi ny cng tr v mt gi tr n bng cu lnh RETURNS. Table Functions : Loi ny tr v mt table http://ebooks.vdcmedia.com HC SQL SERVER 2000 12 Data Type (Loi D Liu) Cc loi d liu trong SQL Server s c bn k trong cc bi sau Expressions Cc Expressions c dng Identifier + Operators (nh +,-,*,/,=...) + Value Cc thnh phn Control-Of Flow Nh BEGIN...END, BREAK, CONTINUE, GOTO, IF...ELSE, RETURN, WHILE.... Xin xem thm Books Online bit thm v cc thnh phn ny. Comments (Ch Thch) T-SQL dng du -- nh du phn ch thch cho cu lnh n v dng /*...*/ ch thch cho mt nhm Thc Thi Cc Cu Lnh SQL Thc thi mt cu lnh n: Mt cu lnh SQL c phn ra thnh cc thnh phn c php nh trn bi mt parser, sau SQL Optimizer (mt b phn quan trng ca SQL Server) s phn tch v tm cch thc thi (Execute Plan) ti u nht v d nh cch no nhanh v tn t ti nguyn ca my nht... v sau SQL Server Engine s thc thi v tr v kt qu. Thc Thi mt nhm lnh (Batches) Khi thc thi mt nhm lnh SQL Server s phn tch v tm bin php ti u cho cc cu lnh nh mt cu lnh n v cha execution plan c bin dch (compiled) trong b nh sau nu nhm lnh trn c gi li ln na th SQL Server khng cn bin dch m c th thc thi ngay iu ny gip cho mt batch chy nhanh hn. Lnh GO Lnh ny ch dng gi mt tn hiu cho SQL Server bit kt thc mt batch job v yu cu thc thi. N vn khng phi l mt lnh trong T-SQL. Tm li trong phn ny chng ta tm hiu v Transact- SQL l ngn ng chnh giao tip vi SQL Server. Trong bi sau chng ta s tip tc bn v cu trc bn trong ca SQL Server . http://ebooks.vdcmedia.com HC SQL SERVER 2000 13 Design and Implement a SQL Server Database Cu Trc Ca SQL Server Nh trnh by cc bi trc mt trong nhng c im ca SQL Server 2000 l Multiple-Instance nn khi ni n mt (SQL) Server no l ta ni n mt Instance ca SQL Server 2000, thng thng l Default Instance. Mt Instance ca SQL Server 2000 c 4 system databases v mt hay nhiu user database. Cc system databases bao gm: Master : Cha tt c nhng thng tin cp h thng (system-level information) bao gm thng tin v cc database khc trong h thng nh v tr ca cc data files, cc login account v cc thit t cu hnh h thng ca SQL Server (system configuration settings). Tempdb : Cha tt c nhng table hay stored procedure c tm thi to ra trong qu trnh lm vic bi user hay do bn thn SQL Server engine. Cc table hay stored procedure ny s bin mt khi khi ng li SQL Server hay khi ta disconnect. Model : Database ny ng vai tr nh mt bng km (template) cho cc database khc. Ngha l khi mt user database c to ra th SQL Server s copy ton b cc system objects (tables, stored procedures...) t Model database sang database mi va to. Msdb : Database ny c SQL Server Agent s dng hoch nh cc bo ng v cc cng vic cn lm (schedule alerts and jobs). Cu Trc Vt L Ca Mt SQL Server Database Mi mt database trong SQL Server u cha t nht mt data file chnh (primary), c th c thm mt hay nhiu data file ph (Secondary) v mt transaction log file. Primary data file (thng c phn m rng .mdf) : y l file chnh cha data v nhng system tables. Secondary data file (thng c phn m rng .ndf) : y l file ph thng ch s dng khi database c phn chia cha trn nhiu da. Transaction log file (thng c phn m rng .ldf) : y l file ghi li tt c nhng thay i din ra trong mt database v cha y thng tin c th roll back hay roll forward khi cn. http://ebooks.vdcmedia.com HC SQL SERVER 2000 14 Data trong SQL Server c cha thnh tng Page 8KB v 8 page lin tc to thnh mt Extent nh hnh v di y: Trc khi SQL Server mun lu data vo mt table n cn phi dnh ring mt khong trng trong data file cho table . Nhng khong trng chnh l cc extents. C 2 loi Extents: Mixed Extents (loi hn hp) dng cha data ca nhiu tables trong cng mt Extent v Uniform Extent (loi thun nht) dng cha data ca mt table. u tin SQL Server dnh cc Page trong Mixed Extent cha data cho mt table sau khi data tng trng th SQL dnh hn mt Uniform Extent cho table . Nguyn Tc Hot ng Ca Transaction Log Trong SQL Server Transaction log file trong SQL Server dng ghi li cc thay i xy ra trong database. Qu trnh ny din ra nh sau: u tin khi c mt s thay i data nh Insert, Update, Delete c yu cu t cc ng dng, SQL Server s ti (load) data page tng ng ln memory (vng b nh ny gi l data cache), sau data trong data cache c thay i(nhng trang b thay i cn gi l dirty-page). Tip theo mi s thay i u c ghi vo transaction log file cho nn ngi ta gi l write-ahead log. Cui cng th mt qu trnh gi l Check Point Process s kim tra v vit tt c nhng transaction c commited (hon tt) vo da cng (flushing the page). http://ebooks.vdcmedia.com HC SQL SERVER 2000 15 Ngoi Check Point Process nhng dirty-page cn c a vo da bi mt Lazy writer. y l mt anh chng lm vic m thm ch thc gic v qut qua phn data cache theo mt chu k nht nh sau li ng yn ch ln qut ti. Xin gii thch thm mt cht v khi nim transaction trong database. Mt transaction hay mt giao dch l mt lot cc hot ng xy ra c xem nh mt cng vic n (unit of work) ngha l hoc thnh cng ton b hoc khng lm g c (all or nothing). Sau y l mt v d c in v transaction: Chng ta mun chuyn mt s tin $500 t account A sang account B nh vy cng vic ny cn lm cc bc sau: 1. Tr $500 t account A 2. Cng $500 vo account B Tuy nhin vic chuyn tin trn phi c thc hin di dng mt transaction ngha l giao dch ch c xem l hon tt (commited) khi c hai bc trn u thc hin thnh cng. Nu v mt l do no ta ch c th thc hin c bc 1 (chng hn nh va xong bc 1 th in cp hay my b treo) th xem nh giao dch khng hon tt v cn phi c phc hi li trng thi ban u (roll back). Th th Check Point Process hot ng nh th no c th m bo mt transaction c thc thi m khng lm "d" database. http://ebooks.vdcmedia.com HC SQL SERVER 2000 16 Trong hnh v trn, mt transaction c biu din bng mt mi tn. Trc nm ngang l trc thi gian. Gi s mt Check Point c nh du vo thi im gia transaction 2 v 3 nh hnh v v sau s c xy ra trc khi gp mt Check point k tip. Nh vy khi SQL Server c restart n s da trn nhng g ghi trong transaction log file phc hi data (xem hnh v). iu c ngha l SQL Server s khng cn lm g c i vi transaction 1 v ti thi im Check point data c lu vo da ri. Trong khi transaction 2 v 4 s c roll forward v tuy c commited nhng do s c xy ra trc thi im check point k tip nn data cha kp lu vo da. Tc l da trn nhng thng tin c ghi trn log file SQL Server hon ton c y c s vit vo da cng. Cn transaction 3 v 5 th cha c commited (do b down bt ng) cho nn SQL Server s roll back hai transaction ny da trn nhng g c ghi trn log file. Cu Trc Logic Ca Mt SQL Server Database Hu nh mi th trong SQL Server c t chc thnh nhng objects v d nh tables, views, stored procedures, indexes, constraints.... Nhng system objects trong SQL Server thng c bt u bng ch sys hay sp. Cc objects trn s c nghin cu ln lt trong cc bi sau do trong phn ny chng ta ch bn s qua mt s system object thng dng trong SQL Server database m thi. http://ebooks.vdcmedia.com HC SQL SERVER 2000 17 Mt s Sytem objects thng dng: System Stored Procedure ng dng Sp_help ['object'] Cung cp thng tin v mt database object (table, view...) hay mt data type. Sp_helpdb ['database'] Cung cp thng tin v mt database c th no . Sp_monitor Cho bit bn rn ca SQL Server Sp_spaceused ['object', 'updateusage' ] Cung cp thng tin v cc khong trng c s dng cho mt object no Sp_who ['login'] Cho bit thng tin v mt SQL Server user V d: sp_helpdb 'Northwind' s cho kt qu c dng nh bng di y name db_size owner dbid created status ..... ------------------------------------------------------------------------------------------------------------------------------- ------Northwind 3.94 MB sa 6 Aug 6 2000 Status=ONLINE, Updateability=READ_WRITE, ..... stored procedure sp_spaceused nh v d sau USE Northwind Go sp_spaceused 'Customers' s cho bit thng tin v table Customer: name rows reserved data index_size unused ------------------------------------- -----------------------------------------Customers 91 104 KB 24 KB 80 KB 0 KB To Mt User Database Chng ta c th to mt database d dng dng SQL Server Enterprise bng cch right-click ln trn "database" v chn "New Database" nh hnh v sau: http://ebooks.vdcmedia.com HC SQL SERVER 2000 18 Sau chng ta ch vic nh tn ca database v click OK. Ngoi ra i khi chng ta cng dng SQL script to mt database. Khi ta phi ch r v tr ca primary data file v transaction log file. V d: USE master GO CREATE DATABASE Products ON ( NAME = prods_dat, FILENAME = 'c:\program files\microsoft SQL server\mssql\data\prods.mdf', SIZE = 4, MAXSIZE = 10, FILEGROWTH = 1 ) GO Trong v d trn ta to mt database tn l Products vi logical file name l prods_dat v physical file name l prods.mdf, kch thc ban u l 4 MB v data file s t ng tng ln mi ln 1 MB cho ti ti a l 10 MB. Nu ta khng http://ebooks.vdcmedia.com HC SQL SERVER 2000 19 ch nh mt transaction log file th SQL s t ng to ra 1 log file vi kch thc ban u l 1 MB. Lu : Khi to ra mt database chng ta cng phi lu mt s im sau: i vi cc h thng nh m vn tc ca server khng thuc loi nhy cm th chng ta thng chn cc gi tr mc nh (default) cho Initial size, Automatically growth file. Nhng trn mt s production server ca cc h thng ln kch thc ca database phi c ngi DBA c lng trc ty theo tm c ca business, v thng thng ngi ta khng chn Autogrowth(t ng tng trng) v Autoshrink(t ng nn). Cu hi c t ra y l v sao ta khng SQL Server chn mt gi tr khi u cho datafile v sau khi cn th n s t ng ni rng ra m li phi c lng trc? Nguyn nhn l nu chn Autogrowth (hay Autoshrink) th chng ta c th s gp 2 vn sau: Performance hit: nh hng ng k n kh nng lm vic ca SQL Server. Do n phi thng xuyn kim tra xem c khong trng cn thit hay khng v nu khng n s phi m rng bng cch dnh thm khong trng t da cng v chnh qu trnh ny s lm chm i hot ng ca SQL Server. Disk fragmentation : Vic m rng trn cng s lm cho data khng c lin tc m cha nhiu ni khc nhau trong da cng iu ny cng gy nh hng ln tc lm vic ca SQL Server. Trong cc h thng ln ngi ta c th d on trc kch thc ca database bng cch tnh ton kch thc ca cc tables, y cng ch l kch thc c on m thi (xin xem "Estimating the size of a database" trong SQL Books Online bit thm v cch tnh) v sau thng xuyn dng mt s cu lnh SQL (thng dng cc cu lnh bt u bng DBCC .Phn ny s c bn qua trong cc bi sau) kim tra xem c khong trng hay khng nu khng ta c th chn mt thi im m SQL server t bn rn nht (nh ban m hay sau gi lm vic) ni rng data file nh th s khng lm nh hng ti performance ca Server. Ch gi s ta dnh sn 2 GB cho datafile, khi dng Window Explorer xem ta s thy kch thc ca file l 2 GB nhng data thc t c th ch chim vi chc MB m thi. Nhng im Cn Lu Khi Thit K Mt Database Trong phm vi bi ny chng ta khng th ni su v l thuyt thit k database m ch a ra mt vi li khuyn m bn nn tun theo khi thit k. http://ebooks.vdcmedia.com HC SQL SERVER 2000 20 Trc ht bn phi nm vng v cc loi data type. V d bn phi bit r s khc bit gia char(10), nchar(10) varchar(10), nvarchar(10). Loi d liu Char l mt loi string c kch thc c nh ngha l trong v d trn nu data a vo "This is a really long character string" (ln hn 10 k t) th SQL Server s t ng ct phn ui v ta ch cn "This is a". Tng t nu string a vo nh hn 10 th SQL s thm khong trng vo pha sau cho 10 k t. Ngc li loi varchar s khng thm cc khong trng pha sau khi string a vo t hn 10. Cn loi data bt u bng ch n cha d liu dng unicode. Mt lu khc l trong SQL Server ta c cc loi Integer nh : tinyint, smallint, int, bigint. Trong kch thc tng loi tng ng l 1,2,4,8 bytes. Ngha l loi smallint tng ng vi Integer v loi int tng ng vi Long trong VB. Khi thit k table nn: C t nht mt ct thuc loi ID dng xc nh mt record d dng. Ch cha data ca mt entity (mt thc th) Trong v d sau thng tin v Sch v Nh Xut Bn c cha trong cng mt table Books BookID Title Publisher PubState PubCity PubCountry 1 Inside SQL Server 2000 Microsoft Press CA Berkely USA 2 Windows 2000 Server MA Boston USA 3 Beginning Visual Basic Wrox 6.0 CA Berkely USA New Riders Ta nn tch ra thnh table Books v table Publisher nh sau: Books BookID Title PublisherID 1 Inside SQL Server 2000 P1 2 Windows 2000 Server P2 3 Beginning Visual Basic 6.0 P3 http://ebooks.vdcmedia.com HC SQL SERVER 2000 21 v Publishers PublisherID Publisher PubState PubCity PubCountry P1 Microsoft Press CA Berkely USA P2 New Riders MA Boston USA P3 Wrox CA Berkely USA Trnh dng ct c cha NULL v nn lun c gi tr Default cho cc ct Trnh lp li mt gi tr hay ct no V d mt cun sch c th c vit bi hn mt tc gi v nh th ta c th dng mt trong 2 cch sau cha data: Books BookID Title Authors 1 Inside SQL Server 2000 John Brown 2 Windows 2000 Server Matthew Bortniker, Rick Johnson 3 Beginning Visual Basic 6.0 Peter Wright, James Moon, John Brown hay Books BookID Title Author1 Author2 Author3 Null Null Matthew Bortniker Rick Johnson Null Peter Wright James Moon John Brown 1 Inside SQL Server 2000 John Brown 2 Windows 2000 Server 3 Beginning Visual Basic 6.0 Tuy nhin vic lp i lp li ct Author s to nhiu vn sau ny. Chng hn nh nu cun sch c nhiu hn 3 tc gi th chng ta s gp phin phc ngay....Trong v d ny ta nn cht ra thnh 3 table nh sau: http://ebooks.vdcmedia.com HC SQL SERVER 2000 22 Books BookID Title 1 Inside SQL Server 2000 2 Windows 2000 Server 3 Beginning Visual Basic 6.0 Authors AuthID First Name Last Name A1 John Brown A2 Matthew Bortniker A3 Rick Johnson A4 Peter Wright A5 James Moon AuthorBook BookID AuthID 1 A1 2 A2 2 A3 3 A4 3 A5 3 A1 Ngoi ra mt trong nhng iu quan trng l phi bit r quan h (Relationship) gia cc table: One-to-One Relationships : trong mi quan h ny th mt hng bn table A khng th lin kt vi hn 1 hng bn table B v ngc li. One-to-Many Relationships : trong mi quan h ny th mt hng bn table A c th lin kt vi nhiu hng bn table B. Many-to-Many Relationships : trong mi quan h ny th mt hng bn table A c th lin kt vi nhiu hng bn table B v mt hng bn table B cng c th lin kt vi nhiu hng bn table A. Nh ta thy trong v d trn mt cun sch c th c vit bi nhiu tc gi v mt tc gi cng c th vit nhiu cun sch. Do mi quan h gia Books v Authors l quan h Many to Many. Trong trng hp ny ngi ta thng dng mt table trung gian gii quyt vn (table AuthorBook). http://ebooks.vdcmedia.com HC SQL SERVER 2000 23 c mt database tng i hon ho ngha l thit k sao cho data cha trong database khng tha khng thiu bn cn bit thm v cc th thut Normalization. Tuy nhin trong phm vi kha hc ny chng ti khng mun bn su hn v ti ny, bn c th xem thm trong cc sch dy l thuyt c s d liu. Tm li trong bi ny chng ta tm hiu v cu trc ca mt SQL Server database v mt s vn cn bit khi thit k mt database. Trong bi sau chng ta s bn v Backup v Restore database nh th no. http://ebooks.vdcmedia.com HC SQL SERVER 2000 24 Backup And Restore SQL Server Chin Lc Phc Hi D Liu (Data Restoration Strategy) C mt iu m chng ta phi ch l hu nh bt k database no cng cn c phc hi vo mt lc no trong sut chu k sng ca n. L mt ngi Database Administrator bn cn phi gim ti a s ln phi phc hi d liu, lun theo di, kim tra thng xuyn pht hin cc trc trc trc khi n xy ra. Phi d phng cc bin c c th xy ra v bo m rng c th nhanh chng phc hi d liu trong thi gian sm nht c th c. Cc dng bin c hay tai ha c th xy ra l: a cha data file hay Transaction Log File hay system file b mt Server b h hng Nhng thm ha t nhin nh bo lt, ng t, ha hon Ton b server b nh cp hoc ph hy Cc thit b dng backup - restore b nh cp hay h hng Nhng li do v ca user nh l tay delete ton b table chng hn Nhng hnh vi mang tnh ph hoi ca nhn vin nh c a vo nhng thng tin sai lc. B hack (nu server c kt ni vi internet). Bn phi t hi khi cc vn trn xy ra th bn s lm g v phi lun c bin php phng c th cho tng trng hp c th. Ngoi ra bn phi xc nh thi gian ti thiu cn phc hi d liu v a server tr li hot ng bnh thng. Cc Loi Backup c th hiu cc kiu phc hi d liu khc nhau bn phi bit qua cc loi backup trong SQL Server Full Database Backups : Copy tt c data files trong mt database . Tt c nhng user data v database objects nh system tables, indexes, user-defined tables u c backup. http://ebooks.vdcmedia.com HC SQL SERVER 2000 25 Differential Database Backups : Copy nhng thay i trong tt c data files k t ln full backup gn nht. File or File Group Backups : Copy mt data file n hay mt file group. Differential File or File Group Backups : Tng t nh differential database backup nhng ch copy nhng thay i trong data file n hay mt file group. Transaction Log Backups : Ghi nhn mt cch th t tt c cc transactions cha trong transaction log file k t ln transaction log backup gn nht. Loi backup ny cho php ta phc hi d liu tr ngc li vo mt thi im no trong qu kh m vn m bo tnh ng nht (consistent). Trong lc backup SQL Server cng copy tt c cc hot ng ca database k c hot ng xy ra trong qu trnh backup cho nn ta c th backup trong khi SQL ang chy m khng cn phi ngng li. Recovery Models Full Recovery Model : y l model cho php phc hi d liu vi t ri ro nht. Nu mt database trong mode 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 : mode 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. Simple Recovery Model : mode ny th Transaction Log File c truncate thng xuyn v khng cn backup. Vi mode 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. Mun bit database ca bn ang mode no bn c th Right-click ln mt database no trong SQL Server Enterprise Manager chn Properties>Options->Recovery http://ebooks.vdcmedia.com HC SQL SERVER 2000 26 Tuy nhin c th ti y bn cm thy rt kh hiu v nhng iu trnh by trn. Chng ta hy dng mt v d sau lm r vn . V d: Chng ta c mt database c p dng chin lc backup nh hnh v sau: Trong v d ny ta schedule mt Full Database Backup vo ngy Ch Nht v Differential Backup vo cc ngy th Ba v Th Nm. Transaction Log Backup c schedule hng ngy. Vo mt ngy Th Su "en ti" mt s c xy ra l a cha data file ca database b h v l mt DBA bn c yu cu phi phc hi d liu v a database tr li hot ng bnh thng. Bn phi lm sao? Trc ht bn phi backup ngay Transaction Log File (Trong v d ny Transaction Log File c cha trong mt a khc vi a cha Data File nn khng b h v vn cn hot ng). Ngi ta cn gi file backup trong trng hp ny l " the tail of the log" (ci ui). Nu Log File c cha trn cng mt a vi Data file th bn c th s khng backup c "ci ui" v nh vy bn phi dng n log file backup gn nht. Khi backup "ci ui" ny bn cn phi dng option NO_TRUNCATE bi v thng thng cc Transaction Log Backup s truncate(xo) nhng phn khng cn dng n trong transaction log file, l nhng transaction c commited v c vit vo database (cn gi l inactive portion of the transaction log) gim kch thc ca log file. Tuy nhin khi backup phn ui khng c truncate m bo tnh consistent (nht qun) ca database. http://ebooks.vdcmedia.com HC SQL SERVER 2000 27 K n bn phi restore database t Full Backup File ca ngy Ch Nht. N s lm 2 chuyn : copy data, log, index... t a backup vo Data Files v sau s ln lt thc thi cc transaction trong transaction log. Lu ta phi dng option WITH NORECOVERY trong trng hp ny (tc l option th 2 "Leave database nonoperational but able to restore additional transaction logs" trong Enterprise Manager). Ngha l cc transaction cha hon tt (incomplete transaction) s khng c roll back. Nh vy database lc ny s trong tnh trng inconsistent v khng th dng c. Nu ta chn WITH RECOVERY (hay "Leave database operational. No additional transaction logs can be restored " trong Enterprise Manager) th cc incomplete transaction s c roll back v database trng thi consistent nhng ta khng th no restore cc transaction log backup c na. Tip theo bn phi restore Differential Backup ca ngy Th Nm. Sau ln lt restore cc Transaction Log Backup k t sau ln Differential Backup cui cng ngha l restore Transaction Log Backup ca ngy Th Nm v "Ci ui". Nh vy ta c th phc hi data tr v trng thi trc khi bin c xy ra. Qu trnh ny gi l Database Recovery. Cng xin lm r cch dng t Database Restoration v Database Recovery trong SQL Server. Hai t ny nu dch ra ting Vit u c ngha l phc hi c s d liu nhng khi c sch ting Anh phi cn thn v n c ngha hi khc nhau. Nh trong v d trn Khi ta restore database t mt file backup ngha l ch n gin ti to li database t nhng file backup v thc thi li nhng transaction c commit nhng database c th trong trng thi inconsistent v khng s dng c. Nhng khi ni n recover ngha l ta khng ch phc hi li data m cn bo m cho n trng thi consistent v s dng c (usable). C th bn s hi consistent l th no? Phn ny s c ni r trong bi sau v Data Integrity. Nhng cng xin dng mt v d n gin gii thch. Trong v d v th no l mt transaction bi 3 : Gi s s tin $500 c tr khi account A nhng li khng c cng vo account B v nu database khng c qu trnh khi phc d liu t ng (automatic recovery process) ca SQL rollback th n s trng thi inconsistent. Nu database trng thi ging nh trc khi tr tin hoc sau khi cng $500 thnh cng vo account B th gi l consistent. Cho nn vic backup Transaction Log File s gip cho vic recovery data ti bt k thi im no trong qu kh. i vi Simple Recovery Model ta ch c th recover ti ln backup gn nht m thi. http://ebooks.vdcmedia.com HC SQL SERVER 2000 28 Nh vy khi restore database ta c th chn option WITH RECOVERY roll back cc transaction cha c commited v database c th hot ng bnh thng nhng ta khng th restore thm backup file no na, thng option ny c chn khi restore file backup cui cng trong chui backup. Nu chn option WITH NORECOVERY cc transaction cha c commited s khng c roll back do SQL Server s khng cho php ta s dng database nhng ta c th tip tc restore cc file backup k tip, thng option ny c chn khi sau ta cn phi restore cc file backup khc. Khng l ch c th chn mt trong hai option trn m thi hay sao? Khng hon ton nh vy ta c th chn mt option trung lp hn l option WITH STANDBY (tc l option 3 "Leave database read-only and able to restore additional transaction logs" trong Enterprise Manager). Vi option ny ta s c lun c tnh ca hai option trn : cc incomplete transaction s c roll back m bo database consistent v c th s dng c nhng ch di dng Read-only m thi, ng thi sau ta c th tip tc restore cc file backup cn li (SQL Server s log cc transaction c roll back trong undo log file v khi ta restore backup file k tip SQL Server s tr li trng thi no recovery t nhng g ghi trn undo file). Ngi ta dng option ny khi mun restore database tr li mt thi im no (a point in time) nhng khng r l c phi l thi im m h mun khng, cho nn h s restore tng backup file dng Standby v kim chng mt s data xem c phi l thi im m h mun restore hay khng (chng hn nh trc khi b delete hay trc khi mt transaction no c thc thi) trc khi chuyn sang Recovery option. Backup Database Trong phn ny chng ta s bn v cch backup database. Nhng trc ht chng ta hy lm quen vi mt s thut ng dng trong qu trnh backup v restore. C nhng t ta s nguyn ting Anh m khng dch. Thut Ng Gii Thch Backup Qu trnh copy ton b hay mt phn ca database, transaction log, file hay file group hnh thnh mt backup set. Backup set c cha trn backup media (tape or disk) bng cch s dng mt backup device (tape drive name hay physical filename) Backup Device Mt file vt l (nh C:\SQLBackups\Full.bak) hay tape drive c th (nh \\.\Tape0) dng record mt backup vo mt backup media. Backup File File cha mt backup set Backup Media Disk hay tape c s dng cha mt backup set. Backup media c th cha nhiu backup sets (v d nh t nhiu SQL Server 2000 backups v t nhiu Windows 2000 backups). Backup Set Mt b backup t mt ln backup n c cha trn backup media. http://ebooks.vdcmedia.com HC SQL SERVER 2000 29 Chng ta c th to mt backup device c nh (permanent) hay to ra mt backup file mi cho mi ln backup. Thng thng chng ta s to mt backup device c nh c th dng i dng li c bit cho vic t ng ha cng vic backup. to mt backup device dng Enterprise Manager bn chn Management->Backup ri Right-click->New Backup Device. Ngoi ra bn c th dng sp_addumpdevice system stored procedure nh v d sau: USE Master Go Sp_addumpdevice 'disk' , 'FullBackupDevice' , 'E:\SQLBackups\Full.bak' backup database bn c th dng Backup Wizard hoc click ln trn database mun backup sau Right-click->All Tasks->Backup Database... s hin ra window nh hnh v sau: Sau da ty theo yu cu ca database m chn cc option thch hp. Ta c th schedule cho SQL Server backup nh k. http://ebooks.vdcmedia.com HC SQL SERVER 2000 30 Restore Database Trc khi restore database ta phi xc nh c th t file cn restore. Cc thng tin ny c SQL Server cha trong msdb database v s cho ta bit backup device no, ai backup vo thi im no. Sau ta tin hnh restore. restore bn Right-click->All Tasks->Restore database... s thy window nh hnh v sau: Nu bn restore t mt instance khc ca SQL Server hay t mt server khc bn c chn From device option v chn backup device (file backup) tng ng . Lu nu bn mun overwrite database c sn vi data c backup bn c th chn option Force restore over existing database nh hnh v sau: http://ebooks.vdcmedia.com HC SQL SERVER 2000 31 Bn c th chn leave database operational hay nonoperational ty theo trng hp nh gii thch trn. Tm li trong bi ny chng ta tm hiu mt cht l thuyt v backup v restore database trong SQL Server. c th hiu r hn bn cn phi thc tp hay lm th c thm kinh nghim. Trong bi sau chng ta s bn v ti Data Integrity ngha l lm sao m bo data cha trong database l ng tin cy v khng b "lng l" nh cch ni bnh dn m ti thng hay dng. Data Integrity and Advanced Query Technique Ni n Data Integrity l ta ni n tnh ton vn ca mt database hay ni mt cch khc l data cha trong database phi chnh xc v ng tin cy. Nu data cha trong database khng chnh xc ta ni database mt tnh ton vn (lost data integrity). Trong bi ny chng ta s bn qua cc phng php gi cho database c ton vn. http://ebooks.vdcmedia.com HC SQL SERVER 2000 32 Cc Phng Php m Bo Data Integrity SQL Server dng mt s cch m bo Data Integrity. Mt s cch nh Triggers hay Index s c bn n trong cc bi sau tuy nhin trong phm vi bi ny chng ta cng ni s qua cc cch trn. Data Type : Data type cng c th m bo tnh ton vn ca data v d bn khai bo data type ca mt ct l Integer th bn khng th a gi tr thuc dng String vo c. Not Null Definitions : Null l mt loi gi tr c bit, n khng tng ng vi zero, blank hay empty string " " m c ngha l khng bit (unknown) hay cha c nh ngha (undefined). Khi thit k database ta nn lun cn thn trong vic cho php mt ct c Null hay Not Null v vic cha Null data c th lm cho mt s ng dng vn khng xa l null data k lng b "t". Default Definitions : Nu mt ct c cho mt gi tr default th khi bn khng a vo mt gi tr c th no th SQL Server s dng gi tr mc nh ny. Bn phi dng Default i vi Not Null definition. Identity Properties : Data thuc dng ID s m bo tnh duy nht ca data trong table. Constraints : y s l phn m ta o su trong bi ny. Constraint tm dch l nhng rng buc m ta dng m bo tnh ton vn ca data. Constraints l nhng quy lut m ta p t ln mt ct m bo tnh chnh xc ca d liu c nhp vo. Rules : y l mt object mang tnh backward-compatible ch yu tng thch vi cc version trc y ca SQL Server. Rules tng ng vi CHECK Constraint trong SQL Server 2000 nhng ngi ta c xu hng s dng CHECK Constraint v n chnh xc hn v c th t nhiu Constraints ln mt ct trong khi ch c mt rule cho mt ct m thi. Ch rule l mt object ring v sau lin kt vi mt ct no ca table trong khi CHECK constraint l mt thuc tnh ca table nn c th c to ra vi lnh CREATE TABLE. Triggers : Mt loi stored procedure c bit c thc thi mt cch t ng khi mt table c Update, Insert, hay Delete. V d ta mun khi mt mn hng c bn ra th tng s hng ha trong kho phi c gim xung (-1) chng hn khi ta c th dng trigger m bo chuyn . Triggers s c bn k trong cc bi sau. Indexes : s c bn n trong bi ni v Indexes. http://ebooks.vdcmedia.com HC SQL SERVER 2000 33 Constraints Constraints l nhng thuc tnh (property) m ta p t ln mt table hay mt ct trnh vic lu d liu khng chnh xc vo database (invalid data). Tht ra NOT NULL hay DEFAULT cng c xem l mt dng constraint nhng chng ta khng bao gm hai loi ny y m ch trnh by 4 loi constraints l Primary Key Constraint, Unique Constraint, Foreign Key Constraint v Check Constraint. Primary Key Constraint: Mt table thng c mt hay nhiu ct c gi tr mang tnh duy nht xc nh mt hng bt k trong table. Ta thng gi l Primary Key v c to ra khi ta Create hay Alter mt table vi Primary Key Constraint. Mt table ch c th c mt Primary Key constraint. C th c nhiu ct tham gia vo vic to nn mt Primary Key, cc ct ny khng th cha Null v gi tr trong cc ct thnh vin c th trng nhau nhng gi tr ca tt c cc ct to nn Primary Key phi mang tnh duy nht. Khi mt Primary Key c to ra mt Unique Index s c t ng to ra duy tr tnh duy nht. Nu trong table cha c Clustered Index th mt Unique + Clustered Index s c to ra. C th to ra Primary Key Constraints nh sau: CREATE TABLE Table1 (Col1 INT PRIMARY KEY, Col2 VARCHAR(30) ) hay CREATE TABLE Table1 (Col1 INT, Col2 VARCHAR(30), CONSTRAINT table_pk PRIMARY KEY (Col1) ) Unique Constraint Bn c th to Unique Constraint m bo gi tr ca mt ct no khng b trng lp. Tuy Unique Constraint v Primary Key Constraint u m bo tnh duy nht nhng bn nn dng Unique Constraint trong nhng trng hp sau: http://ebooks.vdcmedia.com HC SQL SERVER 2000 34 Nu mt ct (hay mt s kt hp gia nhiu ct) khng phi l primary key. Nn nh ch c mt Primary Key Constraint trong mt table trong khi ta c th c nhiu Unique Constraint trn mt table. Nu mt ct cho php cha Null. Unique constraint c th p t ln mt ct cha gi tr Null trong khi primary key constraint th khng. Cch to ra Unique Constraint cng tng t nh Primary Key Constraint ch vic thay ch Primary Key thnh Unique. SQL Server s t ng to ra mt nonclustered unique index khi ta to mt Unique Constraint. Foreign Key Constraint Foreign Key l mt ct hay mt s kt hp ca nhiu ct c s dng p t mi lin kt data gia hai table. Foreign key ca mt table s gi gi tr ca Primary key ca mt table khc v chng ta c th to ra nhiu Foreign key trong mt table. Foreign key c th reference (tham chiu) vo Primary Key hay ct c Unique Constraints. Foreign key c th cha Null. Mc d mc ch chnh ca Foreign Key Constraint l kim sot data cha trong table c Foreign key (tc table con) nhng thc cht n cng kim sot c lun data trong table cha Primary key (tc table cha). V d nu ta delete data trong table cha th data trong table con tr nn "m ci" (orphan) v khng th reference ngc v table cha. Do Foreign Key constraint s m bo iu khng xy ra. Nu bn mun delete data trong table cha th trc ht bn phi drop hay disable Foreign key trong table con trc. C th to ra Foreign Key Constraints nh sau: CREATE TABLE Table1 (Col1 INT PRIMARY KEY, Col2 INT REFERENCES Employees(EmployeeID) ) hay CREATE TABLE Table1 (Col1 INT PRIMARY KEY, Col2 INT, CONSTRAINT col2_fk FOREIGN KEY (Col2) REFERENCES Employees (EmployeeID) ) i khi chng ta cng cn Disable Foreign Key Constraint trong trng hp: http://ebooks.vdcmedia.com HC SQL SERVER 2000 35 Insert hay Update: Nu data insert vo s vi phm nhng rng buc c sn (violate constraint) hay constraint ca ta ch mun p dng cho data hin thi m thi ch khng phi data s insert. Tin hnh qu trnh replicate. Nu khng disable Foreign Key Constraint khi replicate data th c th cn tr qu trnh copy data t source table ti destination table mt cch khng cn thit. Check Constraint Check Constraint dng gii hn hay kim sot gi tr c php insert vo mt ct. Check Constraint ging Foreign Key Constraint ch n kim sot gi tr a vo mt ct nhng khc ch Foreign Key Constraint da trn gi tr table cha cho php mt gi tr c chp nhn hay khng trong khi Check Constraint da trn mt biu thc logic (logic expression) kim tra xem mt gi tr c hp l khng. V d ta c th p t mt Check Constraint ln ct salary ch chp nhn tin lng t $15000 n $100000/nm. Ta c th to ra nhiu Check Constraint trn mt ct. Ngoi ra ta c th to mt Check Constraint trn nhiu ct bng cch to ra Check Constraint mc table (table level). C th to ra Check Constraint nh sau: CREATE TABLE Table1 (Col1 INT PRIMARY KEY, Col2 INT CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000), Col3 VARCHAR(30) ) Trong v d ny ta gii hn gi tr chp nhn c ca ct Col2 t 0 n 1000. V d sau s to ra mt Check Constraint ging nh trn nhng table level: CREATE TABLE Table1 (Col1 INT PRIMARY KEY, Col2 INT, Col3 VARCHAR(30), CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000) ) Tng t nh Foreign Key Constraint i khi ta cng cn disable Check Constraint trong trng hp Insert hay Update m vic kim sot tnh hp l ca data khng p dng cho data hin ti. Trng hp th hai l replication. Mun xem hay to ra Constraint bng Enterprise Manager th lm nh sau: http://ebooks.vdcmedia.com HC SQL SERVER 2000 36 Click ln trn mt table no v chn Design Table-> Click vo icon bn phi "Manage Constraints..." Advanced Query Techniques Trong phn ny chng ta s o su mt s cu lnh nng cao nh SELECT, INSERT... C th ni hu nh ai cng bit qua cu lnh cn bn kiu nh "SELECT * FROM TABLENAME WHERE..." nhng c th c nhiu ngi khng bit n nhng tnh cht nng cao ca n. C php y ca mt cu lnh SELECT rt phc tp tuy nhin y ch trnh by nhng nt chnh ca lnh ny m thi: SELECT select_list [ INTO new_table ] FROM table_source [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ] Chng ta s ln lt nghin cu tng clause (mnh ) trong cu lnh ny. SELECT Clause Sau keyword (t kha) SELECT ta s c mt danh sch cc ct m ta mun select c cch nhau bng du ",". C 3 Keywords cn nhn mnh trong phn SELECT. Distinct : Khi c keyword ny vo th s cho kt qu cc ct khng trng nhau. V d trong Orders table ca Norwind database (database mu di km vi SQL Server) cha gi tr trng lp (duplicate value) trong ct ShipCity. Nu ta mun select mt danh sch ShipCity trong mi city ch xut hin mt ln trong kt qu nhn c ta dng nh sau: SELECT DISTINCT ShipCity, ShipRegion FROM Orders ORDER BY ShipCity Top n : Nu ta mun select n hng u tin m thi ta c th dng Top keyword. Nu c thm ORDER BY th kt qu s c order trc sau mi select. Chng ta cng c th select s hng http://ebooks.vdcmedia.com HC SQL SERVER 2000 37 da trn phn trm bng cch thm Keyword Percent vo. V d sau s select 10 hng u tin theo th t: SELECT DISTINCT TOP 10 ShipCity, ShipRegion FROM Orders ORDER BY ShipCity As : i khi chng ta mun cho SELECT statement d c hn mt cht ta c th dng mt alias (tc l t thay th hay t vit tt) vi keyword As hay khng c keyword As: table_name As table_alias hay table_name table_alias. V d: USE pubs SELECT p.pub_id, p.pub_name AS PubName FROM publishers AS p Ngoi ra trong Select list ta c th select di dng mt expression nh sau: SELECT FirstName + ' ' + LastName AS "Employee Name", IDENTITYCOL AS "Employee ID", HomePhone, Region FROM Northwind.dbo.Employees ORDER BY LastName, FirstName ASC Trong v d trn ta select ct "Employee Name" l sn phm ghp li ca ct FirstName v LastName c cch nhau bng mt khong trng. Mt gi tr thuc loi identity lm ct "Employee ID". Kt qu s c sp theo th t t nh ti ln (ASC) (cn DESC l t ln ti nh) trong ct LastName c sp trc ri mi ti ct FirstName. The INTO Clause INTO Clause cho php ta select data t mt hay nhiu table sau kt qu s c insert vo mt table mi. Table ny c to ra do kt qu ca cu lnh SELECT INTO. V d: SELECT FirstName, LastName INTO EmployeeNames FROM Employers Cu lnh tn s to ra mt table mi c tn l EmployeeNames vi 2 ct l FirstName v LastName sau kt qu select c t table Employers s c insert vo table mi ny. Nu table EmployeeNames tn ti SQL Server s bo li. Cu lnh ny thng hay c s dng select mt lng data ln t nhiu table khc nhau vo mt table mi (thng dng cho mc ch tm thi (temporary table)) m khi phi thc thi cu lnh Insert nhiu ln. http://ebooks.vdcmedia.com HC SQL SERVER 2000 38 Mt cch khc cng select data t mt hay nhiu table v insert vo mt table khc l dng "Insert Into...Select...". Nhng cu lnh ny khng to ra mt table mi. Ngha l ta table phi tn ti trc. V d: INSERT INTO EmployeeNames SELECT FirstName, LastName FROM Employers Ch l khng c ch "Value" trong cu Insert ny. The GROUP BY and HAVING Clauses GROUP BY dng to ra cc gi tr tng (aggregate values) cho tng hng trong kt qu select c. Ch c mt hng cho tng gi tr ring bit (distinct) ca tng ct. Cc ct c select u phi nm trong GROUP BY Clause. Hy xem v d phc tp sau: SELECT OrdD1.OrderID AS OrderID, SUM(OrdD1.Quantity) AS "Units Sold", SUM(OrdD1.UnitPrice * OrdD1.Quantity) AS Revenue FROM [Order Details] AS OrdD1 WHERE OrdD1.OrderID in (SELECT DISTINCT OrdD2.OrderID FROM [Order Details] AS OrdD2 WHERE OrdD2.UnitPrice > $100) GROUP BY OrdD1.OrderID HAVING SUM(OrdD1.Quantity) > 100 Trong v d trn u tin ta select nhng order ring bit (distinct) t Order Details table vi gi > 100. Sau tip tc select OrderID, "Units Sold", Revenue t kt qu trn trong "Units Sold" v Revenue l nhng aggregate columns (cho gi tr tng mt ct ca nhng hng c cng OrderID). HAVING Clause ng vai tr nh mt filter dng lc li cc gi tr cn select m thi. HAVING Clause thng i chung vi GROUP BY mc d c th xut hin ring l. UNION Uninon keyword c nhim v ghp ni kt qu ca 2 hay nhiu queries li thnh mt kt qu. V d: Gi s c table1(ColumnA varchar(10), ColumnB int) v table2(ColumnC varchar(10), ColumnD int). Ta mun select data t table1 v ghp vi data t table2 to thnh mt kt qu duy nht ta lm nh sau: SELECT * FROM Table1 UNION ALL SELECT * FROM Table2 http://ebooks.vdcmedia.com HC SQL SERVER 2000 39 Nu khng c keyword ALL th nhng hng ging nhau t 2 table s ch xut hin mt ln trong kt qu. Cn khi dng ALL th cc hng trong 2 table u c trong kt qu bt chp vic lp li. Khi Dng Union phi ch hai chuyn: s ct select 2 queries phi bng nhau v data type ca cc ct tng ng phi compatible (tng thch). Using JOINS Trong phn ny chng ta s tm hiu v cc loi Join trong SQL Server. Bng cch s dng JOIN bn c th select data t nhiu table da trn mi quan h logic gia cc table (logical relationships). C th tm tt cc loi Join thng dng bng cc hnh sau: Th t t tri sang phi: Inner Join, Left Outer Join, Right Outer Join, Full Outer Join Inner Joins Dng Inner Join select data t 2 hay nhiu tables trong gi tr ca cc ct c join phi xut hin c 2 tables tc l phn gch cho trn hnh. V d: SELECT t.Title, p.Pub_name FROM Publishers AS p INNER JOIN Titles AS t ON p.Pub_id = t.Pub_id ORDER BY Title ASC Left Outer Joins Dng Left Outer Join select data t 2 hay nhiu tables trong tt c ct bn table th nht v khng tn ti bn table th hai s c select cng vi cc gi tr ca cc ct c inner join. S ct select c s bng vi s ct ca table th nht. Tc l phn t mu trn hnh. V d: USE Pubs SELECT a.Au_fname, a.Au_lname, p.Pub_name FROM Authors a LEFT OUTER JOIN Publishers p ON a.City = p.City ORDER BY p.Pub_name ASC, a.Au_lname ASC, a.Au_fname ASC http://ebooks.vdcmedia.com HC SQL SERVER 2000 40 Right Outer Joins Dng Right Outer Join select data t 2 hay nhiu tables trong tt c ct bn table th hai v khng tn ti bn table th nht s c select cng vi cc gi tr ca cc ct c inner join. S ct select c s bng vi s ct ca table th hai. Tc l phn t mu trn hnh. V d: USE Pubs SELECT a.Au_fname, a.Au_lname, p.Pub_name FROM Authors a RIGHT OUTER JOIN Publishers p ON a.City = p.City ORDER BY p.Pub_name ASC, a.Au_lname ASC, a.Au_fname ASC Full Outer Joins Dng Full Outer Join select data t 2 hay nhiu tables trong tt c ct bn table th nht v th hai u c chn cc gi tr bn hai table bng nhau th ch ly mt ln. Tc l phn t mu trn hnh. V d: USE Pubs SELECT a.Au_fname, a.Au_lname, p.Pub_name FROM Authors a FULL OUTER JOIN Publishers p ON a.City = p.City ORDER BY p.Pub_name ASC, a.Au_lname ASC, a.Au_fname ASC Cross Joins Dng Cross Join ghp data t hai table trong s hng thu c bng vi s hng ca table th nht nhn vi s hng ca table th hai. V d: USE pubs SELECT au_fname, au_lname, pub_name FROM authors CROSS JOIN publishers WHERE authors.city = publishers.city ORDER BY au_lname DESC l trong cu lnh ny khng c keyword "On". Mun hiu r hn v cc loi join bn cho chy th trn SQL Server v lm phn bi tp s 1. Tm li trong bi ny chng ta tm hiu data integrity trong SQL Server bng cch dng cc loi Constraint. Ngoi ra Chng ta cng bit qua v mt s k thut query nng cao. Sau bi hc ny cc bn cn lm bi tp s 1 h thng ha li kin thc hc t bi 1 n bi 5 trc khi bn hc tip bi s 6. Khi lm bi tp nh phi lm theo th t v tun th theo cc yu cu ca bi tp t ra. Khng nn b qua bc no. http://ebooks.vdcmedia.com HC SQL SERVER 2000 41 Stored Procedure and Advanced T-SQL Trong bi ny chng ta s tm hiu mt s cch import v export data trong SQL Server. Sau s bn qua cc loi Stored Procedure v Cursor. S dng bcp v BULK INSERT import data bcp l mt command prompt dng import hay export data t mt data file (Text file hay Excel File) vo SQL Server hay ngc li. Thng khi mun chuyn mt s lng ln data t mt database system khc nh Oracle, DB2...sang SQL Server trc ht ta s export data ra mt text file sau import vo SQL Server dng bcp command. Mt trng hp thng dng hn l ta export data t SQL Server sang mt Microsoft Excel file v Excel file ny c th l input cho mt program hay mt database system khc. Chng ta cng c th chuyn data vo SQL Server dng cu lnh BULK INSERT. Tuy nhin BULK INSERT ch c th import data vo trong SQL Server ch khng th export data ra mt data file nh bcp. c th insert data vo SQL Server Database, data file phi c dng bng ngha l c cu trc hng v ct. Ch khi data c bulk copy (copy hng lot dng bcp hay BULK INSERT) vo mt table trong SQL Server th table phi tn ti v data c cng thm vo (append). Ngc li khi export data ra mt data file th mt file mi s c to ra hoc data file s b overwrite nu n tn ti. C php y ca lnh bcp c th xem trong SQL Server Books Online. y ch trnh by mt s v d n gin v cch s dng bcp command v BULK INSERT. V d 1: Gi s bn mun export data t table Orders trong PracticeDB (y l database c to ra trong bi tp s 1 ) ra mt text file trong cc ct c phn cch bng du ";". Bn c th lm nh sau: m DOS command prompt v nh vo dng lnh sau: bcp PracticeDB..Orders out c:\Orders.txt -c T t; Trong v d trn ta mun bulk copy table Orders ra mt text file trong : http://ebooks.vdcmedia.com HC SQL SERVER 2000 42 out: copy data t table hay view ra mt data file (c:\Orders.txt). Ngc li ta c th dng switch in import data t text file vo SQL Server. -c: bulk copy dng kiu d liu Character (Char) (nu khng ch r th SQL Server s dng "TAB" character (\t) phn nh cc ct v dng new line character (\n) phn nh cc hng nh cc gi tr default). -t;: du ";" i sau switch "t" cho bit ta mun dng ";" phn nh cc ct (nu khng s dng gi tr mc nh nh trn) -T: dng (NT) Trust connection kt ni vi database. Ngha l nu user authenticated (cho php) vo c Windows system th ng nhin c s dng SQL Server m khng cn dng thm username v password no khc. V d 2: Thay v copy ton b table ta c th dng query select mt phn data v export ra text file nh sau: bcp "Select * From practiceDB..Orders" queryout c:\Orders.txt -c -SVinhtai -Usa -Pabc Trong v d ny ta select ton b data trong Orders table ra mt text file dng query v SQL Server authentication. queryout : cho bit y l mt query ch khng phi l table. -S : tn ca SQL Server (hay tn ca mt Instance) -U : SQL user name dng log on -P : password dng log on. V d 3 : dng BULK INSERT bulk copy data t text file vo SQL Server database. M Query Analyser (BULK INSERT l mt T-SQL command ch khng phi l mt command prompt utility) v nh vo cc dng sau : BULK INSERT PracticeDB..Orders FROM 'c:\Orders.txt ' WITH (DATAFILETYPE = 'CHAR') Trong v d trn DATAFILETYPE= 'CHAR' cho bit data c cha dng Char data type. N mun dng data type dng unicode th dng 'WIDECHAR' Ch : Cc switch trong bcp command l case-sensitive. Ngha l ch hoa v ch thng s c ngha khc nhau. http://ebooks.vdcmedia.com HC SQL SERVER 2000 43 Distributed Queries i khi chng ta mun select data t nhng database system khc nh MS Access, Oracle, DB2... hay thm ch t mt SQL Server khc ta cn phi dng distributed query. SQL Server s dng k thut OLEDB v cc API chuyn cc query ny ti cc database system khc. C 2 cch truy cp vo cc database system khc l dng LINKED SERVER v Ad Hoc Computer Name. Linked Server: Linked Server l mt server o c dng truy cp vo cc database system khc. Mt khi setup th ta c th query data dng four-part name : linked_server_name.catalog.schema.object_name . Trong catalog thng tng ng vi database name, Schema tng ng vi database owner v object_name tng ng vi table hay view. V d: Gi s ta setup mt Linked Server vo Access database "PracticeDB.mdb" trong cc table u tng t nh PracticeDB database trong SQL Server (c to ra trong phn bi tp s 1). M Enterprise Manager -> Chn node Security ca local server -> Right-Click ln node Linked Server chn New Linked Server. Sau nhp vo tn ca Linked Server LinkedPracticeDB, trong phn Provider Name chn Microsoft Jet 4.0 OLEDB Provider. Trong phn Data Source nhp vo v tr ca Access database (C:\PracticeDB.mdb) v click OK. Ta s c Linked Server tn LinkedPracticeDB xut hin di phn Security/Linked Server. Gi s ta mun select data t Linked Server ny ta c th dng Query Analyser nh sau: Select * from LinkedPracticeDB...Customers Trong v d trn ta dng tn ca Linked Server v theo sau l ba chm (v truy cp vo database ta phi dng four-part name nhng trong trng hp ny ta dng default value nn khng cn cho bit tn ca Catalog v Schema nhng phi dng du chm phn bit tng phn). Ngoi cch trn ta c th dng pass-through query vi OPENQUERY function nh sau: Select * from OPENQUERY(LinkedPracticeDB,'Select * from Customers') http://ebooks.vdcmedia.com HC SQL SERVER 2000 44 Trong v d trn ta thy function OPENQUERY s tr v mt data set v c th nm sau keyword FROM nh mt table. Khi dng OPENQUERY function ta cn cho bit tn ca Linked Server v query m ta mun thc hin. Lu : function trong SQL Server c dng tng t nh l stored procedure. Ad Hoc Computer Name Ngoi cch dng Linked Server nh trnh by trn ta c th dng ad hoc computer name (ad hoc ngha l lm thi, tm thi). Ngha l i vi nhng database system m ta thng xuyn query th dng Linked Server cn i vi nhng query lu lu mi dng n th ta c th select data bng OPENROWSET hay OPENDATASOURCE functions V d: ta cng s select data t Access database nh trn dng OPENROWSET Select * from OPENROWSET('Microsoft.jet.oledb.4.0','C:\PracticeDB.mdb'; 'admin'; '', Customers) Trong v d trn khi dng OPENROWSET ta cn phi a vo tt c nhng thng tin cn thit connect vo database nh tn ca Provider, v tr ca file, username, password (trng hp ny khng c password) v tn ca table m ta mun select. Mi ln ta thc thi cu lnh trn SQL Server u kim tra security trong khi nu dng Linked Server th ch kim ta mt ln m thi. OPENROWSET tng t nh OPENQUERY ch n tr v mt rowset v c th t vo v tr ca mt table trong cu lnh query. Ngoi cch dng trn ta cng c th dng OPENDATASOURCE query nh sau: Select * from OPENDATASOURCE('Microsoft.jet.oledb.4.0', 'Data Source = C:\PracticeDB.mdb; User ID = Admin; Password = ') ...Customers Trong v d trn ta thy OPENDATASOURCE tr v mt phn ca four-part name (ngha l tng ng vi tn ca Linked Server) cho nn ta phi dng thm ba du chm. Cursors Nu gii thch mt cch ngn gn th cursor tng t nh recordset hay dataset trong programming. Ngha l ta select mt s data vo memory sau c th ln lt lm vic vi tng record bng cch Move Next... http://ebooks.vdcmedia.com HC SQL SERVER 2000 45 C 3 loi cursors l Transact- SQL Cursors, API Cursors v Client Cursors. Trong Transact-SQL v API thuc loi Server Cursors ngha l cursors c load ln v lm vic bn pha server. Trong khun kh bi hc ny ta ch nghin cu Transact-SQL cursors. Transact-SQL cursors c to ra trn server bng cc cu lnh Transact-SQL v ch yu c dng trong stored procedures v triggers. Trc ht hy xem qua mt v d v cursor: DECLARE @au_lname varchar(40), @au_fname varchar(20) DECLARE Employee_Cursor CURSOR FOR SELECT LastName, FirstName FROM Northwind.dbo.Employees OPEN Employee_Cursor FETCH NEXT FROM Employee_Cursor INTO @au_lname, @au_fname WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Author:' + @au_fname + ' ' + @au_lname FETCH NEXT FROM Employee_Cursor INTO @au_lname, @au_fname END CLOSE Employee_Cursor DEALLOCATE Employee_Cursor Trong v d trn ta s select LastName v FirstName t Employees table ca Northwind database v load vo Employee_Cursor sau ln lt in tn ca cc employee ra mn hnh. lm vic vi mt cursor ta cn theo cc bc sau: 1. Dng cu lnh DECLARE CURSOR khai bo mt cursor. Khi khai bo ta cng phi cho bit cu lnh SELECTs c thc hin ly data. 2. Dng cu lnh OPEN a data ln memory (populate data). y chnh l lc thc hin cu lnh SELECT vn c khai bo trn. 3. Dng cu lnh FETCH ly tng hng data t record set. C th l ta phi gi cu lnh FETCH nhiu ln. FETCH tng t nh lnh Move trong ADO recordset ch n c th di chuyn ti lui bng cu lnh FETCH FIRST, FETCH NEXT, FETCH PRIOR, FETCH LAST, FETCH ABSOLUTE n, FETCH RELATIVE n nhng khc ch l n ly data b vo trong variable (FETCH...FROM...INTO variable_name). Thng thng ta FETCH data trc sau loop cho ti record cui ca Cursor bng vng lp WHILE bng cch kim tra global variable @@FETCH_STATUS (=0 ngha l thnh cng). http://ebooks.vdcmedia.com HC SQL SERVER 2000 46 4. Khi ta ving thm tng record ta c th UPDATE hay DELETE ty theo nhu cu (trong th d ny ch dng lnh PRINT) 5. Dng cu lnh CLOSE ng cursor. Mt s ti nguyn (memory resource) s c gii phng nhng cursor vn cn c khai bo v c th OPEN tr li. 6. Dng cu lnh DEALLOCATE phng thch hon ton cc ti nguyn dnh cho cursor (k c tn ca cursor). Lu l trong v d trn trc khi dng Cursor ta cng declare mt s variable (@au_fname v @au_lname) cha cc gi tr ly c t cursor. Bn c th dng Query Analyzer chy th v d trn. Stored Procedures Trong nhng bi hc trc y khi dng Query Analyzer chng ta c th t tn v save cc nhm cu lnh SQL vo mt file di dng script c th s dng tr li sau ny. Tuy nhin thay v save vo text file ta c th save vo trong SQL Server di dng Stored Procedure. Stored Procedure l mt nhm cu lnh Transact-SQL c compiled (bin dch) v cha trong SQL Server di mt tn no v c x l nh mt n v (ch khng phi nhiu cu SQL ring l). u im Ca Stored Procedure Stored Procedure c mt s u im chnh nh sau: Performance : Khi thc thi mt cu lnh SQL th SQL Server phi kim tra permission xem user gi cu lnh c c php thc hin cu lnh hay khng ng thi kim tra c php ri mi to ra mt execute plan v thc thi. Nu c nhiu cu lnh nh vy gi qua network c th lm gim i tc lm vic ca server. SQL Server s lm vic hiu qu hn nu dng stored procedure v ngi gi ch gi mt cu lnh n v SQL Server ch kim tra mt ln sau to ra mt execute plan v thc thi. Nu stored procedure c gi nhiu ln th execute plan c th c s dng li nn s lm vic nhanh hn. Ngoi ra c php ca cc cu lnh SQL c SQL Sever kim tra trc khi save nn n khng cn kim li khi thc thi. Programming Framework : Mt khi stored procedure c to ra n c th c s dng li. iu ny s lm cho vic bo tr (maintainability) d dng hn do vic tch ri gia business rules (tc l nhng logic th hin bn trong stored procedure) v database. V d nu c mt s thay i no v mt logic th ta ch vic thay i code bn trong stored procedure m thi. Nhng http://ebooks.vdcmedia.com HC SQL SERVER 2000 47 ng dng dng stored procedure ny c th s khng cn phi thay i m vn tng thch vi business rule mi. Cng ging nh cc ngn ng lp trnh khc stored procedure cho php ta a vo cc input parameters (tham s) v tr v cc output parameters ng thi n cng c kh nng gi cc stored procedure khc. Security : Gi s chng ta mun gii hn vic truy xut d liu trc tip ca mt user no vo mt s tables, ta c th vit mt stored procedure truy xut d liu v ch cho php user c s dng stored procedure vit sn m thi ch khng th "ng" n cc tables mt cch trc tip. Ngoi ra stored procedure c th c encrypt (m ha) tng cng tnh bo mt. Cc Loi Stored Procedure Stored procedure c th c chia thnh 5 nhm nh sau: 1. System Stored Prcedure : L nhng stored procedure cha trong Master database v thng bt u bng tip u ng sp_ . Cc stored procedure ny thuc loi built-in v ch yu dng trong vic qun l database (administration) v security. V d bn c th kim tra tt c cc processes ang c s dng bi user DomainName\Administrators bn c th dng sp_who @loginame='DomainName\Administrators' . C hng trm system stored procedure trong SQL Server. Bn c th xem chi tit trong SQL Server Books Online. 2. Local Stored Procedure : y l loi thng dng nht. Chng c cha trong user database v thng c vit thc hin mt cng vic no . Thng thng ngi ta ni n stored procedure l ni n loi ny. Local stored procedure thng c vit bi DBA hoc programmer. Chng ta s bn v cch to stored prcedure loi ny trong phn k tip. 3. Temporary Stored Procedure : L nhng stored procedure tng t nh local stored procedure nhng ch tn ti cho n khi connection to ra chng b ng li hoc SQL Server shutdown. Cc stored procedure ny c to ra trn TempDB ca SQL Server nn chng s b delete khi connection to ra chng b ct t hay khi SQL Server down. Temporary stored procedure c chia lm 3 loi : local (bt u bng #), global (bt u bng ##) v stored procedure c to ra trc tip trn TempDB. Loi local ch c s dng bi connection to ra chng v b xa khi disconnect, cn loi global c th c s dng bi bt k connection no. Permission cho loi global l dnh cho mi ngi http://ebooks.vdcmedia.com HC SQL SERVER 2000 48 (public) v khng th thay i. Loi stored procedure c to trc tip trn TempDB khc vi 2 loi trn ch ta c th set permission, chng tn ti k c sau khi connection to ra chng b ct t v ch bin mt khi SQL Server shut down. 4. Extended Stored Procedure : y l mt loi stored procedure s dng mt chng trnh ngoi vi (external program) vn c compiled thnh mt DLL m rng chc nng hot ng ca SQL Server. Loi ny thng bt u bng tip u ng xp_ .V d, xp_sendmail dng gi mail cho mt ngi no hay xp_cmdshell dng chy mt DOS command... V d xp_cmdshell 'dir c:\' . Nhiu loi extend stored procedure c xem nh system stored procedure v ngc li. 5. Remote Stored Procedure : Nhng stored procedure gi stored procedure server khc. Vit Stored Procedure Tn v nhng thng tin v Stored Procedure khi c to ra s cha trong SysObjects table cn phn text ca n cha trong SysComments table. V Stored Procedure cng c xem nh mt object nn ta cng c th dng cc lnh nh CREATE, ALTER, DROP to mi, thay i hay xa b mt stored procedure. Chng ta hy xem mt v d sau v Stored Procedure: to mt stored procedure bn c th dng Enterprise Manager click ln trn Stored Procedure -> New Stored Procedure.... Trong v d ny ta s to ra mt stored procedure insert mt new order vo Orders table trong Practice DB. insert mt order vo database ta cn a vo mt s input nh OrderID, ProductName (order mn hng no) v CustomerName (ai order). Sau ta tr v kt qu cho bit vic insert c thnh cng hay khng. Result = 0 l insert thnh cng. CREATE PROCEDURE AddNewOrder @OrderID smallint, @ProductName varchar(50), @CustomerName varchar(50), @Result smallint=1 Output AS DECLARE @CustomerID smallint BEGIN TRANSACTION If not Exists(SELECT CustomerID FROM Customers WHERE [Name]=@CustomerName) --This is a new customer. Insert this customer to the database BEGIN SET @CustomerID= (SELECT Max(CustomerID) FROM Customers) SET @CustomerID=@CustomerID+1 http://ebooks.vdcmedia.com HC SQL SERVER 2000 49 INSERT INTO Customers VALUES(@CustomerID,@CustomerName) If Exists(SELECT OrderID FROM [Orders] WHERE OrderID=@OrderID) --This order exists and could not be added any more so Roll back BEGIN SELECT @Result=1 ROLLBACK TRANSACTION END Else --This is a new order insert it now BEGIN INSERT INTO [Orders](OrderID,ProductName,CustomerID) VALUES(@OrderID,@ProductName,@CustomerID) SELECT @Result=0 COMMIT TRANSACTION END END Else --The customer exists in DB go ahead and insert the order BEGIN If Exists(SELECT OrderID FROM [Orders] WHERE OrderID=@OrderID) --This order exists and could not be added any more so Roll back BEGIN SELECT @Result=1 ROLLBACK TRANSACTION END Else --This is a new order insert it now BEGIN INSERT INTO [Orders](OrderID,ProductName,CustomerID) VALUES(@OrderID,@ProductName,@CustomerID) SELECT @Result=0 COMMIT TRANSACTION END END Print @Result Return to ra mt stored procedure ta dng lnh CREATE PROCEDURE theo sau l tn ca n (nu l temporary stored procedure th thm du # trc tn ca procedure. Nu mun encrypt th dng WITH ENCRYPTION trc ch AS) v cc input hoc ouput parameters. Nu l output th thm keyword OUTPUT ng sau parameter. Ta c th cho gi tr default cng lc vi khai bo data type ca parameter. K t sau ch AS l phn body ca stored procedure. Trong v d trn trc ht ta khai bo mt bin @CustomerID sau bt u mt transaction bng BEGIN TRANSACTION (ton b cng vic insert ny c thc hin trong mt Transaction ngha l hoc l insert thnh cng hoc l http://ebooks.vdcmedia.com HC SQL SERVER 2000 50 khng lm g c- all or nothing). Trc ht ta kim tra xem ngi khch hng l ngi mi hay c. Nu l ngi mi th ta "tin tay" insert vo Customers table lun cn nu khng th ch insert vo Orders table m thi. Nu l ngi customer mi ta ly CustomerID ln nht t Customers table b vo bin @CustomerID v sau tng ln mt n v dng cho vic Insert Customer dng k tip. Sau khi insert ngi customer mi ta tip tc cng vic bng vic kim tra xem Order mun insert c tn ti cha (v nu order tn ti th khi insert SQL Server s bo li do OrderID l Primary key). Nu nh order trn v l do no c trong DB th ta roll back v tr kt qu =1 cn nu khng th ta insert mt order mi vo v commit transaction vi kt qu tr v =0. Tng t nh vy nu ngi customer tn ti (sau ch else u tin) th ta ch vic insert order ging nh trn. Trong mi trng hp k trn ta u in ra kt qu v return. V d trn y ch mang tnh hc hi cn trn thc t database c th phc tp hn nhiu nn vic vit stored procedure i hi kin thc vng chc v SQL v k nng v programming. Mun hiu r hn v bi hc ny bn cn lm bi tp s 2. Tm li trong bi ny chng ta tm hiu mt s k thut import v export data . ng thi bit qua cc cch select data t cc database system khc dng distributed query. Nhng quan trng nht v thng dng nht l cc stored procedures. Bn cn hiu r vai tr ca stored procedure v bit cch to ra chng. V kin thc v database ni chung v SQL Server ni ring kh rng nn trong khun kh mt bi hc chng ti khng th trnh by cn k tng chi tit v i khi c hi dn p cho nn bn cn c i c li nhiu ln nm c chnh v phi xem thm sch (nu khng c sch th phi xem thm SQL Books Online). Sau bi hc ny cc bn cn lm bi tp s 2 h thng ha li kin thc hc. Khi lm bi tp nn lm theo th t v tun th theo cc yu cu ca bi tp t ra. Khng nn b qua bc no. http://ebooks.vdcmedia.com HC SQL SERVER 2000 51 Triggers And Views Trong bi ny chng ta s tm hiu ng dng ca mt loi stored procedure c bit gi l Triggers v dng Views th hin data trong mt hay nhiu table nh th no. Triggers Trigger l mt loi stored procedure c bit c execute (thc thi) mt cch t ng khi c mt data modification event xy ra nh Update, Insert hay Delete. Trigger c dng m bo Data Integrity hay thc hin cc business rules no . Khi no ta cn s dng Trigger: Ta ch s dng trigger khi m cc bin php bo m data intergrity khc nh Constraints khng th tha mn yu cu ca ng dng. Nn nh Constraint thuc loi Declarative Data Integrity cho nn s kim tra data trc khi cho php nhp vo table trong khi Trigger thuc loi Procedural Data Integrity nn vic insert, update, delete xy ra ri mi kch hot trigger. Chnh v vy m ta cn cn nhc trc khi quyt nh dng loi no trong vic m bo Data Integrity. Khi mt database c denormalized (ngc li qu trnh normalization, l mt qu trnh thit k database schema sao cho database cha data khng tha khng thiu) s c mt s data tha (redundant ) c cha trong nhiu tables. Ngha l s c mt s data c cha cng mt lc hai hay nhiu ni khc nhau. Khi m bo tnh chnh xc th khi data c update mt table ny th cng phi c update mt cch t ng cc table cn li bng cch dng Trigger. V d: ta c table Item trong c field Barcode dng xc nh mt mt hng no . Item table c vai tr nh mt cun catalog cha nhng thng tin cn thit m t tng mt hng. Ta c mt table khc l Stock dng phn nh mn hng c thc trong kho nh c nhp v ny no c cung cp bi i l no, s lng http://ebooks.vdcmedia.com HC SQL SERVER 2000 52 bao nhiu (tc l nhng thng tin v mn hng m khng th cha trong Item table c)...table ny cng c field Barcode xc nh mn hng trong kho. Nh vy thng tin v Barcode c cha hai ni khc nhau do ta cn dng trigger m bo l Barcode hai ni lun c synchonize (ng b). i khi ta c nhu cu thay i dy chuyn (cascade) ta c th dng Trigger bo m chuyn . Ngha l khi c s thay i no table ny th mt s table khc cng c thay i theo m bo tnh chnh xc. V d nh khi mt mn hng c bn i th s lng hng trong table Item gim i mt mn ng thi tng s hng trong kho (Stock table) cng phi gim theo mt cch t ng. Nh vy ta c th to mt trigger trn Item table mi khi mt mn c bn i th trigger s c kch hot v gim tng s hng trong Stock table. c im ca Trigger: Mt trigger c th lm nhiu cng vic (actions) khc nhau v c th c kch hot bi nhiu hn mt event. V d ta c th vit mt trigger c kch hot bi bt k event no nh Update, Insert hay Delete v bn trong trigger ta s vit code gii quyt cho tng trng hp. Trigger khng th c to ra trn temporary hay system table. Trigger ch c th c kch hot mt cch t ng bi mt trong cc event Insert, Update, Delete m khng th chy manually c. C th p dng trigger cho View. Khi mt trigger c kch hot th data mi va c insert hay mi va c thay i s c cha trong Inserted table cn data mi va c delete c cha trong Deleted table. y l 2 table tm ch cha trn memory v ch c gi tr bn trong trigger m thi (ngha l ch nhn thy v c query trong trigger m thi). Ta c th dng thng tin trong 2 table ny so snh data c v mi hoc kim tra xem data mi va thay i c hp l trc khi commit hay roll back. (Xem thm v d bn di) C 2 loi triggers (class) : INSTEAD OF v AFTER. Loi INSTEAD OF s b qua (bybass) action kch hot trigger m thay vo s thc hin cc dng lnh SQL bn trong Trigger. V d ta c mt http://ebooks.vdcmedia.com HC SQL SERVER 2000 53 Update trigger trn mt table vi cu INSTEAD OF th khi table c update thay v update SQL Server s thc hin cc lnh c vit sn bn trong trigger. Ngc li loi AFTER (loi default tng ng vi keyword FOR) s thc hin cc cu lnh bn trong trigger sau khi cc action to nn trigger xy ra ri. To Mt Trigger Nh Th No? C php cn bn to ra mt trigger c dng nh sau: CREATE TRIGGER trigger_name ON table_name or view_name FOR trigger_class and trigger_type(s) AS Transact-SQL statements Nh vy khi to ra mt trigger ta phi ch r l to ra trigger trn table no v c trigger khi no (insert, update hay delete. Sau ch AS l cc cu lnh SQL x l cng vic. Ta hy nghin cu mt ng dng thc tin sau. Gi s ta vit mt application cho php user c th Insert, Update v Delete nhng thng tin nm trong database. User ny thng l nhng ngi khng thng tho lm v computer m chng ti thng gi a l "b tm". Vo mt ngy p tri, "b tm" mt my ti xanh n cu cu ta v l tay "delete" nhng thng tin kh quan trng v hy vng ta c th phc hi d liu dm. Nu chng ta khng phng xa trc khi vit application th coi nh cng v phng cu cha v data hon ton b delete. Nhng nu bn l mt "guru" bn s gt g "chuyn ny kh lm!" nhng sau bn ch tn vi pht ng h rollback. Mun lm c chuyn ny chng ta phi dng mt "chiu" gi l Audit (kim tra hay gim st). Tc l ngoi cc table chnh ta s thm cc table ph gi l Audit tables. Bt k hot ng no ng chm vo mt s table quan trng trong database ta u ghi nhn vo trong Audit table. V d khi user update hay delete mt record trong table no th trc khi update hay delete ta s m thm di chuyn record sang Audit table ri mi update hay delete table chnh. Nh vy nu c chuyn g xy ra ta c th d dng rollback (tr record v ch c). http://ebooks.vdcmedia.com HC SQL SERVER 2000 54 V d: Ta c table Orders trong PracticeDB. audit cc hot ng din ra trn table ny ta to ra mt audit table vi tn Aud_Orders vi cc column ging y ht vi Orders table. Ngoi ra ta thm vo 2 columns : Audit_Type : vi cc gi tr c th l 'I','U','D' ghi nhn record c Insert, Update hay Delete Date_Time_Stamp : Data Type thuc loi DateTime dng ghi nhn thi im xy ra s thay i, c vai tr nh mt con du. (Nu trong mi trng nhiu user th ta thm mt column UserID ghi nhn user no thay i). Sau ta s to ra 3 trigger dng cho vic audit nh sau: --Insert Trigger CREATE TRIGGER [AuditInsertOrders] ON [dbo].[Orders] FOR Insert AS insert into aud_orders select *,'I',getdate() From inserted --Update Trigger CREATE TRIGGER [AuditUpdateOrders] ON [dbo].[Orders] for UPDATE AS insert into aud_orders select *,'U',Getdate() from deleted --Delete Trigger CREATE TRIGGER [AuditDeleteOrders] ON [dbo].[Orders] FOR DELETE AS insert into aud_orders select *,'D',getdate() From deleted Trong v d trn khi user insert mt record th record mi va c insert s nm trong inserted table nh trnh by phn trn. Do ta s select tt c cc column trong inserted table cng thm Audit Type "I" v dng hm GetDate() trong SQL Server ly system date time dng cho Date_Time_Stamp column, sau insert vo Aud_Orders table. Tng t vi trng hp Update v Delete, record c update hay delete nm trong deleted table. Nh vy tr li trng hp th d trn nu "b tm" yu cu ta c th vo tm kim trong audit table phc hi li record. Ngoi ra ta c th dng table ny tm ra th phm xo hay sa cha data khi cn thit. http://ebooks.vdcmedia.com HC SQL SERVER 2000 55 to ra hay xem mt trigger bng Enterprise Manager bn lm nh sau: Right-Click ln table m bn mun to trigger->All Tasks-> Manage Triggers. Lu : i Khi ta ch mun trigger thc s hot ng khi mt hay vi column no c Update ch khng phi bt k column no. Khi ta c th dng hm Update(Column_Name) kim tra xem column no c b update hay khng. V d: To mt trigger cho Customer table. Bn trong Trigger (sau ch AS) ta c th kim tra xem nu column First_Name hay Last_Name b thay i th mi hnh ng nu khng th khng lm g c IF UPDATE (first_name) OR UPDATE (Last_Name) BEGIN Do some conditional processing when either of these columns are updated. END Nu mun kim tra nhiu columns ta c th dng hm khc l Columns_Updated() . Xin xem thm trong SQL Server Books Online bit thm chi tit v cch s dng. Views nh ngha mt cch n gin th view trong SQL Server tng t nh Query trong Access database. View c th c xem nh mt table o m data ca n c select t mt stored query. i vi programmer th view khng khc chi so vi table v c th t v tr ca table trong cc cu lnh SQL. c im ca View l ta c th join data t nhiu table v tr v mt recordset n. Ngoi ra ta c th "xo nu" data (manipulate data) trc khi tr v cho user bng cch dng mt s logic checking nh (if, case...). V d: Create View OrderReport As Select OrderID, (case when [Name] is null then 'New Customer' else [Name] end )As CustomerName, ProductName, DateProcessed From Customers Right Outer Join Orders on Customers.CustomerID=Orders.CustomerID http://ebooks.vdcmedia.com HC SQL SERVER 2000 56 Trong v d trn ta ch yu tr v data t Orders table trong PracticeDB nhng thay v display CustomerID vn khng c nhiu ngha i vi user ta s display tn ca customer bng cch join vi Customer table. Nu Customer Name l Null ngha l tn ca customer t order khng tn ti trong system. Thay v Null ta s display "New Customer" d nhn hn cho user. Ni chung cu lnh SQL trong View c th t rt n gin nh select ton b data t mt table cho n rt phc tp vi nhiu tnh nng programming ca TSQL. View Thng c Dng Vo Vic G? View thng c s dng vo mt s cng vic sau: Tp trung vo mt s data nht nh : ta thng dng view select mt s data m user quan tm hay chu trch nhim v loi b nhng data khng cn thit. V d: Gi s trong table ta c column "Deleted" vi gi tr l True hay False nh du mt record b delete hay khng. Vic ny i khi c dng cho vic Audit. Ngha l trong mt ng dng no khi user delete mt record no , thay v ta physically delete record ta ch logically delete bng cch nh du record l c "Deleted" phng user yu cu roll back. Nh vy ch yu ta ch quan tm n data cha delete cn data c nh du deleted ch c khi no cn roll back hay audit m thi. Trong trng hp ny ta c th to ra mt view select data m Deleted=False v lm vic ch yu trn view thay v ton b table. n gin ha vic x l data: i khi ta c nhng query rt phc tp v s dng thng xuyn ta c th chuyn n thnh View v i x n nh mt table, nh vy s lm cho vic x l data d dng hn. Customize data: Ta c th dng view lm cho users thy data t nhng gc khc nhau mc d h ang dng mt ngun data ging nhau. V d: Ta c th to ra views trong nhng thng tin v customer c th hin khc nhau ty login ID l normal user hay manager. Export v Import data: i khi ta mun export data t SQL Server sang cc ng dng khc nh Excel chng hn ta c th dng view join nhiu table v export dng bcp. http://ebooks.vdcmedia.com HC SQL SERVER 2000 57 Khi s dng view ta c th select,insert, update, delete data bnh thng nh vi mt table. V d: Select * From OrderReport Where DateProcessed <'2003-01-01' Lu : Trong Enterprise Edition (v Developer Edition) ta c th to Index cho View nh cho table. Index s c bn n trong cc bi sau. Mun hiu r hn v bi hc ny bn cn lm bi tp s 3. Nh vy trong bi ny chng ta tm hiu Trigger, View trong SQL Server v mt s ng dng ca n. Ni chung view thng c dng tru tng ha (abstract) hay lc raw data (data th) trc khi tr v cho user trong khi trigger thng c dng bo m tnh integrity ca database. Exercise 1: Advanced Query Please follow those steps to practise: 1. Create a new database called PracticeDB (using Enterprise Manager (EP) or Query Analyser (QA)) 2. Create 2 tables and insert data as follows (use EP or QA) : Customers CustomerID Name (Int) (nVarChar(50)) 1 John Nguyen 2 Bin Laden 3 Bill Clinton 4 Thomas Hardy 5 Ana Tran 6 Bob Carr Orders OrderID CustomerID ProductName (Int) (Int) (nvarchar(50)) 1 2 Nuclear Bomb 2 3 Missile 3 2 Jet-1080 4 1 Beers 5 4 Asian Food 6 7 Wine http://ebooks.vdcmedia.com DateProcessed (datetime) 2002-12-01 2000-03-02 2003-08-03 2001-05-12 2002-10-04 2002-03-08 HC SQL SERVER 2000 58 7 8 Milk 2002-05-02 3. Query data using Select statement with the following Join (use QA) a. Inner Join b. Left Outter Join c. Right Outer Join d. Full Outer Join e. Cross Join The result of the query must be displayed in the following format OrderID CustomerName ProductName DateProcessed ( Hints: Based on the data supplied and your knowledge about various kind of joins guess the results then after each select compare it with your guessing to check if what you understand is correct. You also use As keyword or alias in the queries) 4. Using Select * Into...From statement to create a new table called Processed Orders and populate the new table with the data selecting from Orders table Where DateProcessed is earlier than 2002-10-05. (use QA) 5. Using Insert Into...Select statement to get the top 1 record from Orders table and insert into the ProcessedOrders (use QA) 6. Delete a record from ProcessedOrders where the date processed is 2002-10-04. (use QA) 7. Using Union to merge the two data set from Orders and ProcessedOrders into one data set. (use QA) 8. Apply Constraints (use EP or QA) a.Apply the Primary Constraint to the ID column in the tables b. Apply the Foreign Key Constraint in the Orders table. c. Apply the Check Constraint to the DateProcessed column so that the date is within 1970-01-01 2005-01-01 and try to insert invalid data to see if SQL rejects. d. Apply Unique Constraint to the CustomerName column of Customers 9. Back up database and Restore to somewhere else (on a different server or on the same server but with different database name) (use EP or QA) 10. Truncate and Drop the ProcessedOrders table (use QA) http://ebooks.vdcmedia.com HC SQL SERVER 2000 Exercise 2: Manipulate 59 Data and Stored Procedure Please follow those steps to practise: 9. Use bcp to export all data from Orders table of PracticeDB to c:\Orders.txt (or to c:\Orders.csv) 10. Change some data in the c:\Orders.txt and save. Then import to Orders table from the text file using bcp 11. Import Orders.txt to Orders table using BULK INSERT 12. Create a Linked Server LinkedPracticeDB which link to an Access database PracticeDB.mdb (firstly you have to create an Access database similar to PracticeDB in SQL Server and input some data). Then do a select data using fourpart name and OPENQUERY 13. Using ad hoc computer name with OPENROWSET and OPENDATASOURCE functions to select data from PracticeDB.mdb 14. Create the following Cursor DECLARE @au_lname varchar(40), @au_fname varchar(20) DECLARE Employee_Cursor CURSOR FOR SELECT LastName, FirstName FROM Northwind.dbo.Employees OPEN Employee_Cursor FETCH NEXT FROM Employee_Cursor INTO @au_lname, @au_fname WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Author:' + @au_fname + ' ' + @au_lname FETCH NEXT FROM Employee_Cursor INTO @au_lname, @au_fname END CLOSE Employee_Cursor DEALLOCATE Employee_Cursor 15. Create the following stored procedure and try to execute with some values CREATE PROCEDURE AddNewOrder @OrderID smallint, @ProductName varchar(50), @CustomerName varchar(50), @Result smallint=1 Output AS DECLARE @CustomerID smallint BEGIN TRANSACTION If not Exists(SELECT CustomerID FROM Customers WHERE [Name]=@CustomerName) BEGIN http://ebooks.vdcmedia.com HC SQL SERVER 2000 SET @CustomerID= (SELECT Max(CustomerID) FROM Customers) SET @CustomerID=@CustomerID+1 INSERT INTO Customers VALUES(@CustomerID,@CustomerName) If Exists(SELECT OrderID FROM [Orders] WHERE OrderID=@OrderID) BEGIN SELECT @Result=1 ROLLBACK TRANSACTION END Else BEGIN INSERT INTO [Orders](OrderID,ProductName,CustomerID) VALUES(@OrderID,@ProductName,@CustomerID) SELECT @Result=0 COMMIT TRANSACTION END END Else BEGIN If Exists(SELECT OrderID FROM [Orders] WHERE OrderID=@OrderID) BEGIN SELECT @Result=1 ROLLBACK TRANSACTION END Else BEGIN INSERT INTO [Orders](OrderID,ProductName,CustomerID) VALUES(@OrderID,@ProductName,@CustomerID) SELECT @Result=0 COMMIT TRANSACTION END END Print @Result Return 9. Using VB 6 or VB.NET to execute the AddNewOrder stored procedure 10. Using xp_cmdshell extended stored procedure to send a message (xp_cmdshell net send Hello) http://ebooks.vdcmedia.com 60 HC SQL SERVER 2000 61 Exercise 3: Triggers And Views Please follow those steps to practise: 16. Create 3 triggers to audit the changes to the Orders table. Tips: Create an audit table aud_Orders with the same colums as in the Orders table and 2 more colums AuditType(with values either I,U,D) and DateTimeStamp(which will record the date time stamp of changes) Create Update Triggers (Similar to Insert,Delete) : when a record in the Orders table is updated the trigger will move the old record to the audit table(record the date time and mark it as U) 17. Create a view that shows all the orders with the following colums: OrderID,CustomerName,ProductName,DateProcessed,Status Business rules: If CustomerName is a null value New Customer is returned If DateProcessed is later than current date return Pending, if DateProcessed is ealier return History in Status colum. Tips: a. Using Case When ...Then statement in the view b. Using Getdate() function to get the current date time http://ebooks.vdcmedia.com ... View Full Document

HOCSQL

End of Preview

Sign up now to access the rest of the document