Teaching Guide SQL2008

Embed Size (px)

DESCRIPTION

sql

Citation preview

SQL Server 2008

Trng i Hc Bch Khoa H Ni

TI LIU HNG DN GING DYDNH CHO GING VINV Tuyt Trinh

[email protected]

i hc Bch khoa H Ni

Trang 1

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Thng tin chungGio trnh ny gii thiu v SQL Server, mt h qun tr c s d liu ca Microsoft. B gio trnh c bin son da trn nhng ti liu mi nht v SQL Server 2008 vi mc ch cung cp kin thc c bn cng nh cc kin thc cp nht v cng ngh qun tr c s d liu ca Microsoft. Mc ch ca gio trnh l:1. cung cp cho sinh vin cc kin thc c bn v qun tr c s d liu SQL

Server,2. gii thiu mi trng pht trin ng dng vi c s d liu SQL Server, 3. cp nht cc tnh nng mi, cc c im ni tri ca SQL Server 2008.

B gio trnh c bin son v tng hp bao gm: slide bi ging, bi thc hnh (lab), bi tp (exercise), v cc video t hc. Ton b gio trnh u c trnh by bng ting Anh, nhm mc ch nng cao kh nng tip thu, pht trin cc k nng hc v nghin cu bng ting Anh k nng v cng quan trng i vi ngi hc cng ngh thng tin. Cng vi b gio trnh, ti liu hng dn ny (dnh cho gio vin) lm r y tng ca mi bi ging, cc vn m ging vin nn nhn mnh trong tng bi ging cng nh a ra mt s gi y v vic kt hp ging dy ly thuyt vi thc hnh. Gio trnh c th dng lm ti liu tham kho cho sinh vin cc ngnh Cng ngh thng tin, in t, vin thng v tt c nhng ai mun tm hiu v SQL Server.

Phng php ging dyKha hc ny yu cu sinh vin phi c thc hnh nhiu vi cc v d v bi ton thc t rn luyn cc k nng ch khng ch dng li tm hiu ly thuyt. Gio vin nn t chc cc bui hc l thuyt v thc hnh an xen nhau, l thuyt m sinh vin mi hc c th c th hin ngay bng cc bi thc hnh. iu ny gip cho sinh vin nh v hiu k hn nhng g gio vin truyn t, v cng tng s hng th trong vic hc. Mt v d in hnh v vic t chc cc bui hc c p dng nh sau: miTrang 2

SQL Server 2008

Trng i Hc Bch Khoa H Ni

tun hc gm 1 bui ly thuyt v 1 bui thc hnh / bi tp L thuyt Thi lng : 3 tit hc (c th thay i ty theo i tng sinh vin) Thi gian ging slide: t 2 n 2.5 tit hc ty vo ni dung bi ging v i tng hc. - Thi gian cn li, gio vin c th t chc cho sinh vin nghe cc on video v tin hnh tho lun. Vic an xen cho sinh vin nghe cc bi trnh by ting Anh c th tn kh nhiu thi gian. Do , gio vin nn cn i vic chia thi gian v chn lc cc bi trnh by cho sinh vin nghe v tho lun trn lp. Cc phn khc c th giao cho sinh vin v nh t nghe ri tr li cu hi ca gio vin bui sau ln lp trao i. Thc hnh - Sinh vin thc hnh vi cc bi lab c thit k cho tng ni dung ly thuyt tng ng. - Thng qua v d c th trnh by trong ti liu hng dn thc hnh (hands-on-lab), ging vin hng dn sinh vin thc hin cc bi thc hnh tng bc mt. - Sinh vin t thc hin cc bi tp khc di s hng dn ca ging vin - Kt thc mi bui thc hnh (hoc u bui hc ly thuyt tip theo), ging vin nn tng kt li ni dung bi thc hnh (v bi tp), cc vn chung m sinh vin gp phi cng rt kinh nghim. Bn cnh cc bi thc hnh theo tng ch , gio vin nn yu cu sinh vin thc hin mt bi tp tng hp (project, tm gi l n mn hc). bi cho n mn hc c th do sinh vin t ng ky v/hoc tham kho t mt danh sch cc ti mu la chn, hoc cho php sinh vin t ng k. Vic la chn ti c th c thc hin vo gia hc k hoc vo cui k. rn luyn k nng lm vic nhm cho sinh vin, gio vin c th yu cu lp phn chia thnh cc nhm sinh vin lm cc ti. Ty vo ln ca ti m gio vin quy nh s lng thnh vin ca mt nhm (nn giao ng trong khong t 2 n 4 sinh vin). Khi bt u thc hin v trong qu trnh thc hin n mn hc, gio vin cn c mt tham gia cng sinh vin, hng dn sinh vin i ng hng v hiu vn mt cch chnh xc.Trang 3

SQL Server 2008

Trng i Hc Bch Khoa H Ni

cng chi titGio trnh c chia lm 15 chng. Ni dung ca mi chng s c ging dy trong mt bui ly thuyt v mt bui hng dn thc hnh v/hoc lm bi tp.

Chng 1: Tng quan v SQL ServerBi ging : Session 1: Overview of SQL Server Ni dung : 1.1 Introduction to SQL Server Database 1.2 Relational Data Model 1.3 Data Access Architectures 1.4 SQL Server Services & Tools 1.5 Transact-SQL Language 1.6 CLR integration in SQL Server 1.7 Evolution of SQL Server Bi tp : Exercise1 Video training

Chng 2: B cng c Management StudioBi ging : Session 2: Management Studio Ni dung : 2.1 Integrated Management Environement 2.2 Navigation 2.3 Administering Databases 2.4 Maintaining Databases 2.5 Writing and Executing Transact-SQL with Query Editor 2.6 Working with Templates, Solutions, Script Projects, and Source Control Bi thc hnh Lab2 Bi tp : Video training Exercise2

Chng 3: Thao tc d liu vi T-SQLBi ging : Session 3: T-SQL for Data ManipilationTrang 4

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Ni dung : 3.1 Data Manipulation Language 3.2 Selecting Records from Existing Table 3.3 Subqueries, Joins, Operations on Collection 3.4 Inserting Data into a Table 3.5 Updating Data in Table 3.6 Deleting Data from Table 3.7 Top-k queries 3.8 Full-text Search Bi thc hnh Lab 3 Bi tp : Exercise 3 Video training

Chng 4: nh ngha d liu vi T-SQLBi ging : Session 4: T-SQL for Data Definition Ni dung : 4.1 Data Definition Language 4.2 Managing Databases 4.3 Data Types 4.4 Managing Tables 4.5 Managing other SQL Server Database Objects Bi thc hnh Lab 4 Bi tp : Exercise 4 Video training

Chng 5: Bo mt c s d liu SQL ServerBi ging: Sesion 5: Securing Database and T-SQL for Data Control

Trang 5

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Ni dung : 5.1 Understanding SQL Server Security Model 5.2 Managing logins, users, roles 5.3 Managing permissions 5.4 Data Control Language and Security Issues 5.5 Implementing Security through Database Objects 5.6 Other Security Options Bi thc hnh Lab 5 Bi tp : Exercise 5 Video training

Chng 6: Th tc lu tr trong v hm ngi dngBi ging: Session 6: Stored Procedures and User-Defined Functions Ni dung : 6.1 Understanding the concepts of batch and batch processing 6.2 Control statements 6.3 Defining and assigning variables 6.4 Implementing stored procedures 6.5 Implementing User-Defined Functions 6.6 Difference between Stored Procedures and User-Defined Functions Bi thc hnh Lab 6 Bi tp : Exercise 6 Video training

Chng 7: TriggerBi ging: Session 7: Implementing Triggers Ni dung :Trang 6

SQL Server 2008

Trng i Hc Bch Khoa H Ni

7.1 Introduction to Triggers 7.2 Creating, Altering, and Dropping Triggers 7.3 Working with Triggers 7.4 Uses of Trigger 7.5 Performance Consideration Bi thc hnh Lab 7 Bi tp : Exercise 7 Video training

Chng 8: Lp trnh SQL Server vi .NetBi ging: Session 8: Programming SQL Server with .Net Ni dung : 8.1.Net Framework 8.2 ADO.net 8.3 CLR Integration 8.4 Enabling CLR Integration 8.5 CLR Integration: Pros & Cons Bi thc hnh Lab 8 Bi tp : Exercise 8 Video training

Chng 9: Rng buc ton vnBi ging: Session 9: Implementing Data Integrity Ni dung : 9.1 Types of Data Integrity 9.2 Enforcing Data Integrity 9.3 Defining Constraints 9.4 Types of Constraints 9.5 Disability Constraints 9.6 Using Defaults and Rules 9.7 Deciding Enforcement Method to Use

Trang 7

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Bi thc hnh Lab 9 Bi tp : Exercise 9 Video training

Chng 10: Qun ly giao dch v khaBi ging: Session 10: Managing Transactions and Locks Ni dung : 10.1 Transaction 10.2 Review of Transaction Log in SQL Server 10.3 Managing Transactions 10.4 Managing Locks Understanding SQL Server Locking Architecture Bi thc hnh Lab 10 Bi tp : Exercise 10 Video training

Chng 11: nh ngha v to ch mcBi ging: Session 11: Planning and Creating Index Ni dung : 11.1 Introdution to Indexes 11.2 Understanding Index Architecture 11.3 Retrieving Stored Data with SQL Server 11.4 Defining Indexes 11.5 Creating Indexes 11.6 Maintaining Index Bi thc hnh Lab 11 Bi tp : Exercise 11 Video training

Chng 12: Ti u ha truy vnBi ging: Session 12: Optimizing Query Performance Ni dung :

Trang 8

SQL Server 2008

Trng i Hc Bch Khoa H Ni

12.1 Introduction to the Query Optimizer 12.2 Tuning Performance Using SQL Utilities 12.3 Using an Index to Cover a Query 12.4 Using Views to Optimize Performance 12.5 Overriding the Query Optimizer 12.6 Understanding Indexing Strategies and Guidelines Bi thc hnh Lab 12 Bi tp : Exercise 12 Video training

Chng 13: Phin bn SQL Server 64-bitBi ging: Session 13: SQL Server 64 bit Ni dung : 13.1 Overview of database performance and scalability 13.2 SQL Server 2005 Components 13.3 Advantages of 64-bit environment 13.4 Consideration for choosing SQL Server 64-bit 13.5 Deployment consideration Video training

Chng 14: Cc dch v d liuBi ging: Session 14: Data Platform Vision Ni dung : 14.1 Overview of Microsoft Data Platform Vision 14.2 Integration Services 14.3 Data Analysis Services 14.4 Reporting Services Bi thc hnh Lab 14 Bi tp : Exercise 14 Video training

Trang 9

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Chng 15: Nhng c im mi ca SQL Server 2008Bi ging: Session 15: New Features in SQL Server 2008 Ni dung : 15.1 Policy-based Management 15.2 Optimized and Predictable System Performance 15.3 Dynamic Development 15.4 Beyond Relational Database 15.5 Pervasive Business Insight Bi thc hnh Lab 15 Bi tp : Exercise 15 Video training

Trang 10

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CTng quan v SQL Server 2008Cc ni dung m ging vin cn chuyn ti n ngi hc gm-

HNG 1

Chng ny nhm mc ch gii thiu khi qut (hoc nhc li) cc kin thc c bn v c s d liu v gii thiu tng quan v SQL Server.

Vai tr v li ch ca vic s dng c s d liu trong qun ly thng tin d liu ca ngi dng: t mt kch bn thc t, ging vin cn ch ra cc cch tip cn lu tr v qun ly d liu (tp v CSDL), nu cc c im (im mnh v hn ch) ca tng cch tip cn. Vai tr ca h qun tr c s d liu trong vic khai thc v qun tr c s d liu Cc khi nim c bn v m hnh d liu quan h: bng/quan h, bn ghi/dng d liu, thuc tnh (attributes), min gi tr (domain), kha (primary key, foreign key) Tm hiu khi qut v cc m hnh truy nhp d liu SQL Server: m hnh tp trung, m hnh khch/ch, m hnh hng dch v. Ging vin c th t chc tho lun v cc c im, u/nhc im ca tng m hnh kin trc ny. y, ging vin cng nn a ra cc gi y v kh nng p dng v la chn p dng cc m hnh kin trc ny ty tng iu kin pht trin ng dng c th. Tm hiu khi qut v kin trc bn trong ca SQL Server: cc thnh phn (components) v dch v (services). y, ging vin cng nn lm r cc thnh phn c bn (bt buc) i vi h qun tr c s d liu (c th l: qun ly lu tr, qun ly truy vn v qun tr giao dch) v cc thnh phn thm vo cung cp gi tr gia tng cho x ly d liu trn SQL Server (v d nh dch v tch hp d liu, dch v phn tch d liu, dch v to bo co, ) Tm hiu khi qut v cc ngn ng lp trnh h tr trong SQL Server: Transact-SQL (hay T-SQL) v CLR. Ging vin nn ch r s khc nhau gia cc ngn ng lp trnh ny v phm vi ng dng hiu qu. Mt vi nt v qu trnh pht trin v tin ha ca h qun tr c s d liu SQL Server. y, ging vin nn nhn mnh vo cc khc bit c bn gia cc th h qun tr c s d liu: Th h 2 l m rng ca th h 1 v kh nng nh ngha kiu d liu ca ngi dng v mt s dch v phn tch dTrang 11

-

-

-

-

-

SQL Server 2008

Trng i Hc Bch Khoa H Ni

liu. Th h 3 (SQL Server 2005 v SQL Server 2008) l bc nhy vt nh tch hp CLR bn trong li ca h qun tr c s d liu SQL Server. Nu khi qut cc c im ni tri ca SQL Server 2008. Cc dch v h tr ca SQL Server cho php bo v d liu mi ni, mi lc.

Trong gi bi tp, ging vin c th a ra cc yu cu v tm hiu v thit k c s d liu. Mc ch ca gi bi tp ny l gip sinh vin nh li hoc tm hiu k hn v cu trc c s d liu quan h nh ci t trong SQL Server. Cc bi tp nn tp trung vo: Tm hiu cu trc d liu ca mt c d liu c sn: gii thch chi tit cc khi nim v c s d liu quan h nu trn lp Thit k mt c s d liu cho bi ton c th

Trang 12

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CCng c Management StudioCc ni dung m ging vin cn chuyn ti n ngi hc gm:- Cc thnh phn chc nng

HNG 2

Chng ny nhm mc ch gii thiu v cng c Management Studio, mt mi trng tch hp cho php truy nhp, cu hnh, qun tr v lp trnh vi SQL Server.

- Gii thiu giao din ha cho php thao tc vi cc i tng ca c s d

liu SQL Server. Ging vin nn c bit nhn mnh vo 2 c im ni bt ca b cng c l (i) ca s hin th v qun ly cc mu (template explorer) v (ii) kh nng kt ni ng thi n nhiu my ch SQL Server (registered servers) - Vi cng c thit k bng v thit k s quan h, Management Studio cho php ngi dng d dng to cc bng v cc lin kt thng qua giao din ha. Ging vin cn ch r s tng ng trong vic xy dng s quan h (diagram) v nh ngha kha ngoi cho tng bng.- Cng c h tr son tho v thc hin cc truy vn Query Editor. Khi gii thiu

v cng c ny, ging vin nn nhn mnh n x ly va thng bo li c php v ng ngha ca cu truy vn. Ging vin gii thch cch hiu v x ly cc thng bo li thng thng.- Mt trong nhng tin ch m Management Studio h tr ngi lp trnh l qun

ly scripts ca mt d n. Mt d n l mt tp hp cc script v cc files c mi lin h logic vi nhau. Tp hp ny gm cc thng tin v qun tr v pht trin mt c s d liu. Nhng thng tin v mt d n gm o Thng tin kt ni: tn my ch, c s d liu, giao thc, kiu xc thc, Cc thng tin ny c lu trong 1 script.o

Script SQL s dng bi ngi dng c th c lu tr trong nhiu tp cc tp c phn m rng .sql v c th c son tho vi Query Editor

o Script MDX, DMX, XMLA o V cc tp lu tr cc thng tin khc ca mt d n Trong phn trnh by ny, ging vin nn nu v d v mt s d n trn thc t, x xc nh cc thng tin, x ly cn thit cho qun tr v pht trin d n nu trn. Da trn , ging vin cn lm r li ch ca tin ch h tr trong ManagementTrang 13

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Studio. Trong gi thc hnh v bi tp, ging vin nn thi gian cho hc vin thc hnh cc ni dung: -

ci t v cu hnh SQL Server s dng mt c s d liu mu tm hiu v cc thnh phn chc nng ca Management Studio xy dng c s d liu thit k trc s dng cng c v qun tr d liu v script d n vi SQL Server

Trang 14

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CNgn ng thao tc d liu T-SQLNi dung m ging vin cn chuyn ti n sinh vin bao gm:-

HNG 3

Ngn ng Transact-SQL (vit tt T-SQL) ca SQL Server ci t chun AINSI SQL 92. Cc cu lnh ca T-SQL c chia lm 3 loi l (i)ngn ng thao tc d liu, (ii) ngn ng nh ngha d liu v (iii) ngn ng iu khin d liu. Chng ny tp chung vo trnh by c php cc cu lnh T-SQL thao tc vi mt c s d liu nh ngha v c bit nhn mnh n cc im mi ca ngn ng ci t trong SQL Server 2008

Gii thiu c php chung cu lnh Select-From-Where: Ging vin nn s dng cc v d c th minh ha kh nng biu din yu cu thao tc d liu vi cu lnh SQL. V T-SQL l mt ci t c th ca chun SQL 92, ging vin cng nn lm r cc c im ca ci t ny so vi chun SQL 92 v cc ci t khc (nu sinh vin tng lm quen vi cc ci t khc ca SQL). Sau khi sinh vin nm chc cch vit mt cu lnh SQL n gin, ging vin s gii thiu cc mnh ORDER BY, COMPUTE, GROUP BY, gii thch v cu lnh join, outer-join, ging vin khng ch cn gii thiu c php cu lnh m phi ch ra cc v d c th minh ha v cc trng hp s dng chung V d: a ra danh sch sinh vin v cc kha hc m sinh vin ng ky v a ra danh sch sinh vin v cc kha hc m sinh vin ng ky (nu c) Gii thiu c php v cch vit cc cu truy vn lng nhau (subqueries, join, union): Ngoi vic hng dn sinh vin vit cc cu truy vn dng ny theo c php trnh by, ging vin nn hng dn c cch s dng cc mu c sn (trong ca s template explorer) xy dng cc cu lnh ny.-

-

Gii thiu cc cu lnh cp nht d liu nh thm (Insert), sa (update) v xa (delete): Ging vin nn nu v d c vi nhng cu lnh cp nht tng bn ghi v cu lnh cp nht nhiu bn ghi ng thi nh s dng kt hp vi cc cu lnh c gii thiu trc .-

Mt trong nhng m rng quan trong ca SQL Server l cho php biu din v nh gi cc cu truy vn top-k, cc cu truy vn ny s tr v kt qu l k bn ghi tha mn iu kin tm kim thay v tr v tt c cc bn ghi tm thyTrang 15

SQL Server 2008

Trng i Hc Bch Khoa H Ni

trong c s d liu (k do ngi dng xc nh thng qua cu truy vn). thc hin vic la chn k. Ging vin cn gii thch cc hm Top %, Rank, Dense_Rank Mt m rng khc ca SQL Server l h tr tm kim trn ni dung cc trng d liu (Full-text Search). h tr dng tm kim ny, SQL Server m rng cu lnh truy vn SQL truyn thng vi hai mnh la CONTAINS v FREETEXT. Kiu tm kim ny c h tr t cc phin bn trc ca SQL Server di dng cc dch v gia tng xong t phin bn 2008, tm kim trn ni dung c tch hp hon ton bn trong m-t c s d liu (database engine). Nu c iu kin, ging vin nn gii thch y ngha v mc ch ca ci tin ny ca SQL Server 2008.-

Trong gi thc hnh v bi tp, ging vin nn thi gian cho hc vin thc hnh vit cc cu lnh SQL thc hin cc thao tc trn c s d liu to. Hc vin cng nn s dng kt hp gia cc tin ch khc nhau ca mi trng SQL Server nh trnh son tho truy vn hay s dng cc mu (template) c trong qu trnh xy dng cc cu truy vn SQL.

Trang 16

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CNi dung m ging vin cn chuyn ti n sinh vin bao gm:-

HNG 4

Ngn ng nh ngha d liu T-SQLChng ny tp chung vo trnh by c php cc cu lnh T-SQL cho nh ngha d liu v nhn mnh n cc kiu d liu mi c ci t trong phin bn mi nht SQL Server 2008.

Phm vi ca ngn ng nh ngha d liu gii hn bi cc cu lnh thc hin to mi (create), sa i (alter), xa (drop) cc i tng d liu trong c s d liu (table, view, index, stored procedures, ). Ging vin cng nn phn loi cc i tng ny v sau , ch tp trung vo 2 i tng chnh lin quan n qun ly v hin th d liu l table v view. Cc i tng khc s c cp n trong cc chng c lin quan n sau. Khi gii thch c php cu lnh CREATE DATABASE, ging vin cn gii thch k ngha ca cc tham s v cc la chn ca cu lnh. Nu iu kin cho php, ging vin nn trnh by v gii thch cc cu lnh trc tip trn my c th d dng minh ha chi tit y ngha ca tng mnh Gii thiu cc kiu d liu h tr trong SQL Server gm cc kiu d liu nh ngha sn (built-in data type) v kiu d liu ngi dng nh ngha (userdefined data type). Ging vin nn nhn mnh v kh nng biu din m rng ca SQL Server so vi c s d liu quan h truyn thng thng qua nh ngha cc kiu d liu ngi dng. Sau , ging vin s tp trung vo gii thiu 7 kiu d liu mi c h tr trong SQL Server 2008 SQL Server 2008 h tr thm 4 kiu d liu ngy thng: date, time, datetimeoffset, datetime2. Ging vin cn so snh 4 kiu d liu mi ny vi 2 kiu d liu ngy thng (datetime v smalldatetime) h tr t cc phin bn trc, nu mt s v d minh ha lm r y ngha thc tin ca vic s dng cc kiu d liu mi ny SQL Server 2008 h tr kiu d liu mi HierarchyID cho php biu din mi lin h gia cc gi tr trong mt bng. Ging vin cn nu mt vi v d thc t sinh vin thy r y ngha ca kiu d liu ny v tnh thc tin ca vic h tr kiu d liu ny trong cc ng dng khc nhau. SQL Server 2008 h tr 2 kiu d liu Geography v Geometry biu din v lu tr cc i tng d liu khng gian. Thng qua cc v d ng dng cTrang 17

-

-

-

-

-

SQL Server 2008

Trng i Hc Bch Khoa H Ni

th, ging vin cn lm cho sinh vin hiu r cc i tng d liu khng gian cn lu tr nh im (point), ng (linestring), . Bn cnh , ging vin cn nu r cc im khc bit gia 2 kiu d liu khng gian m SQL Server 2008 h tr. Thng qua vic trnh by thao tc vi cc i tng khng gian (nh tnh khong cch, tm vng ct nhau, giao nhau,), ging vin cn lm r cc li ch i vi ngi lp trnh, pht trin ng dng thng qua vic h tr kiu d liu khng gian bn trong h qun tr c s d liu.-

Khi gii thiu v kh nng h tr lu tr XML bn trong SQL Server, ging vin nn ch r kh nng kim tra tnh hp l ca d liu XML da trn mt lc nh ngha trc. Trc khi gii thiu v mt kiu d liu mi h tr lu tr cc ti liu (vn bn hay a phng tin) FileStream, ging vin cn gii thch mt s gii php cho vic lu tr ti liu c ln, so snh cc gii php ny v nhn mnh vo cc u im m kiu d liu FileStream h tr cho qun ly cc ti liu kch thc ln. Lu y: mt s kiu d liu nh HierarchyID, Geography, Geometry, thc cht l cc CLR types cho php nh ngha c cc phng thc thao tc vi d liu. Chi tit v cch nh ngha CLR type s c cp n trong bi ging v tch hp .net trong SQL Server. Tuy nhin, ging vin cng cn ch ra s khc bit gia cc kiu d liu ny vi cc kiu d liu truyn thng trong cc h qun tr c s d liu quan h.

-

-

Trong gi thc hnh v bi tp, ging vin nn thi gian cho hc vin thc hnh vit cc cu lnh SQL nh ngha v cp nht cu trc c s d liu . Hc vin cng nn s dng kt hp gia cc tin ch khc nhau ca mi trng SQL Server nh s dng cc mu (template) sn c hay cc cng c ha trong qu trnh xy dng cc yu cu nh ngha d liu.

Trang 18

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CBo mt c s d liu SQL Server

HNG 5

Bo mt c s d liu nhm mc ich kim tra tnh hp php ca truy nhp d liu cng nh tnh an ton ca thng tin. Da trn cc cng c qun tr h thng, ngi qun tr c s d liu phi a ra quyt nh cho php hay khng cho php ngi dng truy cp v thao tc trn cc i tng c s d liu. Chng ny tp trung vo trnh by cc gii php bo mt c s d liu trong SQL Server v tho lun v phm vi cng nh hiu qu ca cc phng php bo mt c p dng. Ni dung m ging vin cn chuyn ti n sinh vin bao gm:-

M hnh bo mt ca SQL Server: y, ging vin cn lm r cc mc bo mt khc nhau c th cung cp khi lm vic vi c s d. C th l: bo mt mc h iu hnh, bo mt chun ( mc h qun tr c s d liu SQL Server) v bo mt mc c s d liu. Qun ly quyn ngi dng: Quyn ca ngi dng c nh ngha nh kh nng ngi dng c th thao tc vi c s d liu. Mt cch khi qut, quyn ca ngi dng c th c chia lm 4 loi nh sau: (i) quyn truy nhp vo h qun tr c s d liu, (ii) quyn truy xut c s d liu, (iii) quyn thc hin trn cc i tng ca c s d liu v (iv) quyn x ly d liu Vai tr ca ngi dng trn h qun tr c s d liu v trn c s d liu. Ging vin cn nhn mnh s khc nhau gia 2 loi bo mt khc nhau. Vi mi loi, ging vin cn gii thch chi tit cc vai tr m h thng c th gn cho ngi dng trong qu trnh thao tc vi h thng Ngn ng iu khin d liu: Ging vin gii thiu c php v cch s dng cc cu lnh trong ngn ng T-SQL nh ngha v phn quyn ngi dng (cu lnh: Grant, Revoke, deny). Bn cnh , ging vin cng nn cp n cc phng php nh ngha v phn quyn cho ngi dng thng qua b cng c Management Studio, thng qua cc th tc ca h thng

-

-

-

-

Bo mt c s d liu thng qua cc i tng ca c s d liu nh khung nhn (view), th tc lu tr trong (stored procedures), : hiu r c k thut ny, ging vin cn a ra minh ha v phn cp v mi lin quan gia cc i tng trong mt c s d liu SQL Server. Qua , ging vin giiTrang 19

SQL Server 2008

Trng i Hc Bch Khoa H Ni

thch v mc ph thuc v phm vi nh hng khi thc hin phn quyn ngi dng trn cc i tng ny.-

Mt s k thut bo mt khc nh s dng ti khon, m ha, cng nn c gii thiu. Mt im cn c bit lu y l bo mt h c s d liu khng ch n gin l bo mt c s d liu. N cn lin quan n bo mt h qun tr c s d liu, bo mt ng dng (mi trng thc thi ng dng), bo mt h iu hnh trn chy h c s d liu, bo mt my ch web v mi trng mng c kt ni c s d liu. sinh vin c th hiu r thng ip trn, ging vin nn nhc li khi nim v h c s d liu thy r v tr ca n trong cc ng dng thc t.

Trong bi thc hnh, sinh vin phi s dng cc cng c khc nhau nh ngha cc yu cu bo mt cng nh m bo vic thc hin cc yu cu ny.

Trang 20

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CNi dung m ging vin cn chuyn ti n sinh vin bao gm:-

HNG 6

Th tc lu tr trong v hm ngi dngTh tc lu tr trong v hm ngi dng l nhng thnh phn rt quan trng trong c s d liu SQL Server. Chng ny trnh by cch thc to (vit) v s dng th tc v hm cng nh li ch ca vic s dng cc th tc/hm ny trong thao tc vi c s d liu

Gii thch khi nim x ly b. Trong SQL Server, Transact-SQL (hay T-SQL) l mt ngn ng lp trnh c bn nht. N cho php ta nh ngha cc yu cu thao tc (thm, xa, sa) trn cc bng d liu. Tuy nhin, c php ca T-SQL ch tp trung vo thao tc d liu trn cc bng m cha c cc thnh phn x ly, iu khin. Ging vin cn ch r kh nng a cc cu trc iu khin, cc bin vo trong cu lnh T-SQL. Da trn cu trc m rng , T-SQL c kh nng biu din cc yu cu thao tc phc tp hn ca ngi dng. Cch ci t th tc lu tr trong v hm ngi dng: c php cu lnh v cch xy dng hm, th tc thng qua cng c Management Studio. Ging vin cn nhn mnh nhng im ging v khc nhau khi vit v khi s dng th tc v hm, cch truyn tham s, Nu c thi gian, ging vin nn gii thch qu trnh thc hin ca mt th tc lu tr trong ch ra li ch ca vic s dng chng. Ging vin cng nn gii thiu mt s th tc lu tr trong ca h thng hay c s dng

-

-

Trong gi thc hnh, sinh vin tin hnh xy dng cc th tc, hm v kim tra vic s dng chng

Trang 21

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CTrigger

HNG 7

Trigger l mt dng c bit ca th tc lu tr trong (stored procedures) dng phn hi cc s kin c th. Trigger gm mt on m c gn vi bng d liu v c t ng kch hot khi c mt s kin xc nh trc c xy ra. Bi tnh cht , triggers khng th nhn cc tham s u vo nh hm, th tc v cng khng c gi tr tr v nh hm. Chng ny trnh by v cch to v s dng trigger khi xy dng mt ng dng c s d liu. Ni dung m ging vin cn chuyn ti n sinh vin bao gm: -

nh ngha v trigger: Ging vin cn gii thch cho sinh vin c im ca trigger v so snh n vi th tc lu tr trong v hm ngi dng Gii thch c php cu lnh to trigger: ging vin cn nhn mnh n lin kt bt buc gia mt trigger v mt bng, cc s kin m trigger c th gn vo c kch hot (INSERT, UPDATE, DELETE) v so snh mnh FOR | AFTER vi mnh INSTEAD OF. Gii thch v hot ng ca trigger: ging vin nn a ra mt s tnh hung s dng trigger v hng dn sinh vin phn tch hot ng ca cc trigger ny. T phn tch v nhn xt, ging vin nhn mnh li ch ca vic s dng trigger trong mt s trng hp cng nh cc bt li gp phi khi cc trigger khng c s dng mt cch hp ly. T , ging vin hng dn sinh vin tm ra cc trng hp s dng trigger tt o S dng trigger m bo cc rng buc ton vn o S dng kim tra cc rng buc mt cch uyn chuyn hn o S dng trigger kim tra quy tc rng buc o S dng cc trigger c tnh quy o S dng trigger thc hin theo th to

-

S dng trigger thc hin thay th cc x ly ngm nh nh thm, xa, sa

-

Mt im quan trng khc trong khai thc cc trigger m ging vin cng cn cp l vic s dng cc hm UPDATE() v COLUMNS_UPDATED(). CcTrang 22

SQL Server 2008

Trng i Hc Bch Khoa H Ni

hm ny ch c hiu lc trong phm vi ca mt trigger v cho bit chi tit vic cp nht c tc dng trn tng trng d liu c th no trong bng. Ging vin nn nu mt s v d gip sinh vin thy r ch li ca vic s dng cc hm ny.-

Cng nh nhiu i tng khc ca c s d liu SQL Server, to v cp nht cc trigger c th c thc hin thng qua cu lnh CREATE TRIGGER hay s dng giao din ca Management Studio. Ging vin nn gii thiu c hai cch to trigger v sinh vin thc hnh vi c hai cch ny trong gi thc hnh

Trong gi thc hnh, sinh vin thc hin to cc trigger, chy th v kim tra hot ng ca cc trigger lm sng t cc li ch ca vic s dng trigger ng cch cng nh cc bt li m vic s dng trigger mt cch ty tin, khng hp ly mang li.

Trang 23

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CLp trnh SQL Server vi .Net

HNG 8

.Net framework l mt mi trng pht trin ng dng vi mt th vin lp trnh phong ph h tr cho xy dng giao din, kt ni c s d liu, m ha,Trong .Net framework, CLR (Common language runtime) l thnh phn quan trng nht, m bo mi trng thc thi chng trnh trn nn .net Chng ny tp trung vo trnh by v lp trnh SQL Server vi .Net. Khng ch dng li vic xy dng cc ng dng trn nn .net kt ni n c s d liu thng qua ADO.net, SQL Server 2008 tch hp CLR bn trong li h qun tr c s d liu cho php vit cc truy vn d liu, nh ngha cc kiu d liu mi v vit cc on chng trnh x ly bn trong SQL Server vi mt ngn ng bt k trn .net. Ni dung m ging vin cn chuyn ti n sinh vin bao gm:-

Nhc li cc c im c bn ca .Net: Do chng ny trnh by su vo vic khai thc v vit chng trnh .net trong mt c s d liu SQL Server, sinh vin cn phi c lm quen vi .net v t nht mt ngn ng lp trnh trn .net. Vi i tng sinh vin cha c khi nim v cha quen thuc vi .net, ging vin nn sp xp c th trnh by k hn trc khi ging dy chng ny. Gii thch v ADO.net: y, ging vin cn gii thch r c ch thc hin kt ni c s d liu qua ADO.net. Theo m hnh ny, pha ng dng m kt ni n c s d liu, truy cp d liu, lu tr d liu trong b nh trong trong qu trnh thao tc vi d liu, gi li d liu cp nht v ng kt ni. Ging vin cn lm r u nhc im ca m hnh kt ni d liu ny. Tt hn, ging vin c th a ra cc tnh hung, t chc tho lun t sinh vin c th pht hin ra cc c im ca m hnh. Trnh by v tch hp CLR bn trong c s d liu SQL Server: Ging vin cn trnh by r m hnh ng dng m trong ta c th vit v khai thc CLR. Phn trnh by ny i hi phi c v hiu nhiu m chng trnh. Nu c iu kin, ging vin nn kt hp gia trnh by ly thuyt, xem demo chng trnh v phn tch m lnh ca chng trnh demo. T cc trnh by chi tit v tch hp CLR v cc v d, ging vin hng dn sinh vin tho lun tm ra u v nhc im ca vic s dng m lnh CLRTrang 24

-

-

-

SQL Server 2008

Trng i Hc Bch Khoa H Ni

v a ra cc ch dn cho vic la chn gia s dng SQL CLR v T-SQL. Trong gi thc hnh, hc vin c th s dng cc demo i km tm hiu v cch vit m lnh CLR trong cc i tng c s d liu SQL Server. i vi chng ny, phn bi tp c vai tr c bit quan trng. l cch tt nht nh gi mc tip thu v hiu bi ca sinh vin. Nu c iu kin, ging vin nn t chc cc nhm sinh vin, mi nhm s la chn mt bi ton gii quyt mt cch trn vn.

Trang 25

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CRng buc ton vn. Ni dung m ging vin cn chuyn ti n sinh vin bao gm: -

HNG 9

Theo nh ngha, c s d liu l mt tp hp thng tin c lin h logic vi nhau. Mt mt, mi lin h logic ny c quy nh bi ng ngha d liu a vo trong c s d liu, mt khc, mi lin h ny c nh ngha thng qua cc rng buc v d liu. Cc rng buc ny c dng kim tra khi c s bin i t pha d liu nh thm, xa, cp nht. Trong chng ny, chng ta s tm hiu chi tit v rng buc d liu v cc phng php m bo rng buc ton vn ca d liu.

Cc loi rng buc: Ging vin cn tm cc v d thc t minh ha v cc loi rng buc nh rng buc v min gi tr, rng buc kha chnh, rng buc kha ngoi, rng buc duy nht, rng buc kim tra, rng buc gi tr mc nh, rng buc theo quy tc hay quy lut. Ging vin cn nhn mnh vo 2 loi rng buc mi ch c h tr t SQL Server 2005 l (i) cascade update v (ii) cascade delete. Cascade update dng kim tra rng buc khi cp nht thng tin xem s thay i trong d liu c vi phm vo cc rng buc nh ngha hay khng. Cascade delete kim tra rng buc khi xa thng tin v cp nht thng tin (nu cn) m bo nhng thay i mi trong c s d liu khng vi phm vo cc rng buc nh ngha trc . Rng buc quy lut v rng buc gi tr ngm nh l mt s kiu nh ngha rng buc d liu. y, ging vin cng nn thn trng a ra khuyn co ca Microsoft v vic rng buc quy lut s khng c h tr trong phin bn tip theo ca SQL Server 2008 (theo ti liu trc tuyn v SQL Server 2008). V vy, chng ta cng nn thn trong khi s dng nh ngha rng buc ny cho cc ng dng ang v s pht trin. Triggers v th tc lu tr trong l cc k thut d c tm hiu t cc chng trc. y, mc d chng ta khng cp li ti n, ging vin cng nn c nhng lin h c th v vic s dng n trong vic kim tra v m bo cc rng buc ton vn v d liu. im quan trng nht trong chng ny l so snh cc phng thc m bo rng buc ton vn d liu. T , ta c th a cc khuyn co v vic sTrang 26

-

-

-

-

SQL Server 2008

Trng i Hc Bch Khoa H Ni

dng cc phng thc khc nhau ny trong kim tra cc rng buc ton vn ca d liu. Trong gi thc hnh, ging vin hng dn sinh vin thc hin vic nh ngha cc rng buc v thc hin kim tra rng buc d liu thng qua cc v d c th trn my. Nu c iu kin, sinh vin nn chy cc v d trong ch thc hin tng bc mt c gng gii thch nhn xt so snh qu trnh kim tra cc rng buc d liu khc nhau thng qua cc phng thc khc nhau.

Trang 27

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CQun tr giao dch v kha-

HNG 10

Chng ny trnh by v vn qun tr giao dch trong cc h c s d liu. Giao dch c coi l n v thc hin nh nht trong h c s d liu. Ni dung m ging vin cn chuyn ti n sinh vin bao gm: nh ngha v giao dch: Ging vin nn s dng cc v d thc t minh ha cho khi nim giao dch v ti sao phi qun ly giao dch. V d in hnh m ta c th s dng y l mt giao dch chuyn tin gia 2 ti khon ngn hng. Gio vin gii thch cc hnh ng c th c th thc hin giao dch chuyn tin, t tnh hung cc s c xy ra trong qu trnh thc thi giao dich v pht hin cc vn v d liu xy ra nu khng c mt c ch qun ly thch hp. Nu c iu kin, ging vin nn trnh by cho tit tnh cht ACID ca giao dch, ngha ca vic m bo cc tnh cht ny trong qun ly thc thi cc giao dch. Thng qua v d minh ha, ging vin nn thi gian cho sinh vin tm hiu v tho lun v cc gii php m bo hot ng thng sut ca cc giao dich. T , ta xc nh cc php ton c bn trong thc thi giao dich nh BEGIN, COMMIT, ROLLBACK, SAVE Nu c iu kin, ging vin nn dnh thi gian gii thiu chi tit v cu trc nht ky (log) ca SQL Server. Nht ky h c s d liu c nhim v lu gi (trn a cng) tt c cc thng tin c lin quan n thay i nh DELETE, UPDATE, INSERT. Ging vin cn gii thch cc thi im cn to check point v ghi thng tin ghi nht ky. Li v phc hi li cng l mt vn cn c cp n. Nu c thi gian, ging vin nn gii thch chi tit v cc k thut ny. y chnh l k thut c bn trong qun tr giao dch. Thit lp v khai thc cc giao dch khng tng minh (khng s dng vi cu lnh BEGIN TRAN, COMMIT TRAN, ROLLBACK TRAN) cng nn c cp n trong chng ny. Khi ni n qun tr giao dch, ngi ta khng th khng ni n vn qun ly truy nhp tng tranh v kha. Thng qua mt v d c th (nh giao dch ngn hng), ging vin cn lm r khi nim v truy nhp tng tranh, cc vn gp phi v gii thiu v k thut kha nh mt gii php c bn cho vn ny. Da trn cc tnh hung c th, ging vin gii thiu cc loi kha vTrang 28

-

-

-

-

-

-

SQL Server 2008

Trng i Hc Bch Khoa H Ni

cch thc khai thc chng m bo iu khin truy nhp tng tranh.-

Nu c iu kin, ging vin c th cp n mt vi k thut kha nh kha 2 pha, kha vi nhn thi gian, v phn tch so snh cc k thut ny

Trong gi thc hnh, sinh vin cn vit cc module (cc th tc) v chy th xem tc ng ca cc lnh qun tr giao dch v vai tr ca kha trong qun tr giao dch

Trang 29

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CLp k hoch v to ch mcNi dung m ging vin cn chuyn ti n sinh vin bao gm:-

HNG 11

Chng ny trnh by v vic xc nh v to ch mc trn cc bng d liu. Ch mc l cch t chc lu tr d liu trn b nh ngoi nhm ci thin tc truy nhp d liu. Chng ny tp trung vo tm hiu cch t chc v khai thc ch mc trong h qun tr c s d liu SQL Server.

ngha ca vic s dng ch mc trong truy nhp thng tin trn b nh ngoi: Ging vin nn la chn mt s v d v tm kim d liu minh ha r tc dng, vai tr ca ch mc. Cc hnh thc t chc lu tr ch mc: y ging vin cn gii thiu chi tit cc kiu ch mc m SQL Server h tr. Thng qua mt vi cu truy vn minh ha, ging vin lm cho sinh vin hiu r ch mc c s dng nh th no khi thc hin truy vn v y ngha ca n. Nu c thi gian, ging vin nn yu cu sinh vin thc hin phn tch v tnh ton phc tp ca tng kiu t chc ch mc. Thng qua , sinh vin s ch ra kiu ch mc no ph hp vi tng yu cu truy vn khc nhau. Ging vin cng cn gii thiu chi tit c php cc cu lnh to mi, thay i v xa ch mc trong c s d liu SQL Server, c bit cn lu gii thch cc la chn vi FILLFACTOR, PAD_INDEX Da trn phn tch v tc ng ca s dng ch mc trong truy nhp d liu, ging vin lm r vai tr v y ngha ca vic la chn xy dng hp ly cc ch mc. Tuy nhin, hiu qu ca ch mc li ph thuc nhiu yu t, t yu cu s dng (c th l cc yu cu truy cp d liu t pha ngi dng hay ng dng) n t chc lu tr ch mc ny trn a. SQL Server cung cp mt cng c tr gip tp hp cc thng s v hot ng v s dng ch mc ca h thng. Ngi dng c th phn tch cc thng s ny cng vi cc khuyn co m cng c h tr ca SQL Server a ra iu chnh cc nh ngha ch mc nhm nng cao hiu nng hot ng ca h thng.

-

-

-

Trang 30

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CTi u ha truy vn

HNG 12

Mc ch ca ti u ha truy vn l tm ra mt chin lc tt nht thc hin mt yu cu tm kim u vo ca ngi dng. Ty theo yu cu tm kim, t chc d liu v ni dung d liu lu tr trong c s d liu, h thng s d on mt chin lc nh gi cu truy vn Chng ny gii thiu v mt cng c ca SQL Server cho php theo di (monitoring) v tr gip qu trnh ti u truy vn cng nh a ra cc thng tin cn thit cho vic ti u thit k mt c s d liu Ni dung m ging vin cn chuyn ti n sinh vin bao gm:-

Gii thiu v nguyn tc ca ti u ha truy vn: Ti u ha truy vn l mt vn kh phc tp. Vi thi lng 1 bui hc chng ta kh c th trnh by tng tn v cc k thut ti u ha. y, ging vin nn la chn mt s v d minh ha c th c th lm ni bt cc yu t nh hng n vic la chn chin lc nh gi truy vn nh: s tn ti ca ch s trn mt bng no , kch thc cc bng d liu, phn b ca gi tr mt trng d liu no , y chnh l cc thng s m cng c gim st (monitoring) ca SQL Server thu thp trong qu trinh thc thi truy vn. Bn cnh , ging vin cng cn gii thiu (nhc li) cc php ton i s quan h c bn nh php chn, php chiu, kt ni, v cy ton t. y l nhng khi nim ht sc c bn c th hiu c cng vic ca mt b ti u ha cng nh cc nguyn tc c bn nht ca n. Nhng kin thc ny l cn thit hiu cc kt qu kt xut ca cng c Tuning Advisor Gii thch khi nim v workload v SQL Profiler, cc thng s m tin tch ca SQL Server thu thp trong qu trnh thc thi cc truy vn. SQL Server cung cp cc tin ch cho php ngi dng c th thao tc (ghi li) cc thng tin trung gian trong qu trnh x ly thng qua vic lu li cy ton t trong b nh v cc thng tin thng k trong cc lnh STATISTICSTIME, STATISTICSPROFILE, STATISTICSIO, SHOWPLAN_ALL, SHOWPLAN_TEXT Output. Da trn v d mu, ging vin nn gii thch cho sinh vin ngha v kt qu tr v t cc lnh ny, mi lin h vi thc hin truy vn v nhng yu t nh hng n hiu nng ca thc thi truy vn Bn cnh , SQL Server cn cung cp mt s tin ch nh gi hiu qu caTrang 31

-

-

SQL Server 2008

Trng i Hc Bch Khoa H Ni

cc nh ngha ch mc. Da trn tn sut s dng cc ch mc ny, h thng s a cc khuyn co v vic nn duy tr hay khng nn duy tr cc ch mc. Ging vin nn gii thch (nhc li) vai tr ca ch mc trong vic nng cao hiu qu ca tm kim.

Trang 32

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CPhin bn SQL Server 64 bit-

HNG 13

Chng ny trnh by tng quan v phin bn 64 bit:li ich v trin vng. Ni dung m ging vin cn chuyn ti n sinh vin bao gm: Tng quan v nh gi hiu nng c s d liu v tnh kh chuyn ca c s d liu Tnh tng thch gia SQL Server 32 bit v 64-bit Cc thnh phn ca SQL Server phin bn 64 bit Li ch ca mi trng 64-bit Mt s vn cn xem xt v trin khai vi vi SQL Server 64-bit

-

Trang 33

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CCc dch v d liu-

HNG 14

H qun tr SQL Server khng ch cung cp cc cng c cho php lu tr v qun tr d liu. N cn bao gm cc dch v x ly d liu. Trong chng ny, chng ta cp n 3 dch v d liu l dch v tch hp, dch v phn tch v dch v lp bo co. Ni dung m ging vin cn chuyn ti n sinh vin bao gm: Tng quan v SQL Server v cc dch v h tr thao tc v x ly d liu. y, ging vin nn lm r mi quan h v h tr ln nhau gia cc dch v d liu da trn nn cng ngh ca Microsoft. Dch v phn tch: Ging vin cn gii thiu v m hnh d liu a chiu. Da trn ,ging vin s nu ln yu cu i vi bi ton phn tch d liu v gii thiu cc tin ch m dch v phn tch d liu ca Microsoft h tr Dch v sinh bo co h tr pht trin vic sn sinh cc bo co phc tp trong cc ng dng Dch v tch hp cung cp gii php tch hp cho d liu t nhiu ngun d liu khc nhau. Nu c iu kin, ging vin cng nn gii thch tng quan v cc k thut tch hp d liu sinh vin c c ci nhn tng th hn v vn ny

-

-

Trang 34

SQL Server 2008

Trng i Hc Bch Khoa H Ni

C-

HNG 15

Cc c im mi ca SQL Server 2008Chngny trnh by v mt s c im ca phin bn 2008 t gc nhn ca ngi pht trin ng dng. Ni dung m ging vin cn chuyn ti n sinh vin bao gm: Cc c im ca SQL Server 2008 H tr cc kiu d liu mi trong SQL Server 2008 Cc nng cp v dch v d liu trong SQL Server 2008 Cc h tr mi cho truy cp v thao tc d liu SQL Server 2008

Trang 35

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Ti liu tham kho[1] Biil Hamilton. Programming SQL Server 2005. OReilly, 2006 [2] Robert Vieira. Beginning Microsoft SQL Server 2008 Programming. Wrox, 2008. [3] Rodney Landrum, Shawn McGehee and Walter J. Voytec. Pro SQL Server 2008 Reporting Services, Apress, 2008 [4] Robert D. Schneider and Darril Gibson. Microsoft SQL Server 2008 All-in-One Desk Reference For Dummies, 2008. [5] Thomas Rizzo, Adam Machanic, Robin Dewson, Rob Walters, Joseph Sack, Julian Skinner, Louis Davidson. Pro SQL Server 2005, Apress, 2006. [6] Rob Walters, Michael Coles, Robin Dewson, Fabio Claudio Ferracchiata, Jan D. Narkiewicz, and Robert Rae. Accelerated SQL Server, Apress, 2008.

Trang 36

SQL Server 2008

Trng i Hc Bch Khoa H Ni

PBi thc hnh (Mu)Hands-on Lab

H LC

Programming SQL Server with .NetObjectiveEstimated time to complete this lab: 60 minutes SQL CLR integration is one of the most controversial features of SQL Server. It does have benefits in terms of simplifying conditional logic and performing complex calculation and string manipulation. However, you should always try to use the T-SQL SET-based equivalents of your queries before moving your code to .NET After completing this lab you will be able to: Work with SQL Server Projects Work with the in-process managed provider Leverage the .NET Framework in database development Understand managed code permissions Creating user-defined aggregates

ContentThis lab consists of the following exercises:

Working with SQL Server ProjectsLeveraging the .NET Framework in Database Development Understanding Managed Code Permissions

Creating User-Defined Aggregates

Trang 37

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Exercise 1: Working with SQL Server Projects In this exercise, you will learn how to work with Visual Studio and Microsoft SQL Server in tandem by creating a SQL Server project, and a basic user-defined function whose implementation is in managed code. Then you will build a Windows Form application that displays the result returned from the user-defined function. The goal of this exercise is to lay a foundation for subsequent exercises by introducing how Visual Studio and Microsoft SQL Server work together.

Task 1: Creating a SQL Server Project1. Start Visual Studio .2. Select the File | New | Project menu command.

Visual Studio displays the New Project dialog: .1 In the Project Types pane, indicate that you want to create a Visual C# project..2 In the Templates pane, select SQL Server Project.

.3 In the Name field, enter SqlServerProject. .4 In the Location field, enter "C:\SQL Labs\User Projects"..5 Click OK.

Visual Studio displays the Connection Properties dialog box (as shown in Figure 2).

Figure 2: The Connection Properties dialog box A SQL Server project is associated with a specific database. This dialog box lets you select the database to which you will be deploying managed code. DatabaseTrang 38

SQL Server 2008

Trng i Hc Bch Khoa H Ni

References are shown in the Solution Explorer and become part of the Visual Studio environment. As you open and close different projects, Database References are saved so they can be reused.

Task 2: Creating a Database Reference

1. In the server name field, enter localhost.2. Select Use Windows NT Integrated security.

3. In the database field, enter AdventureWorks.4. Click OK to dismiss the Add Database Reference dialog box.

Task 3: Using a User-Defined Function Template1. In the Solution Explorer, right-click SqlServerProject and select Add | New Item

from the context menu.2. In the Add New Item dialog box, click User-Defined Function. 3. Click Add.

In SQL Server, a user-defined function is similar to a function in other programming languages. Unlike a stored procedure, which can return only an integer or result set, a user-defined function can return a variety of data types. You also can treat a userdefined function similarly to a table or view, issuing SELECT statements directly against the function. In prior versions of SQL Server, you could only create a userdefined function using T-SQL. With Microsoft SQL Server , you can now create userdefined functions using managed code. Visual Studio includes a pre-defined template to use in your SQL Server Projects to make the process easier. 4. In the Solution Explorer, open the TestScripts folder, right-click test.sql and select Open. Notice that when you used the User-Defined Function template, Visual Studio automatically added an additional file to your project named test.sql. You can use the script in test.sql for debugging your code. This script performs the actions in the database that are required to start and test your database object. 5. In the Solution Explorer, right-click Function1.cs and select View Code. 6. In the Code Editor, before the closing bracket, type the following code: [SqlFunction] public static System.DateTime GetTodaysDate() { return System.DateTime.Today; } 7. In the Solution Explorer, right-click test.sql and select Open. 8. Change the first line to:

Trang 39

SQL Server 2008

Trng i Hc Bch Khoa H Ni

select dbo.GetTodaysDate() Task 4: Deploying a .NET Assembly to SQL Server1. In the Solution Explorer, right-click SqlServerProject and select Deploy.

Before an assembly can be used by a database, it must first be deployed to the database server. Visual Studio makes deploying an assembly to Microsoft SQL Server easy to do. Just by right-clicking the project name in the Solution Explorer and selecting the Deploy menu item, Visual Studio will automatically build and deploy your assembly to Microsoft SQL Server . The assembly is also deployed and debugged simply by pressing F5. 2. Once the deployment process has completed, press F5. Note If execution stops on an ALTER PROCEDURE statement, press F5 again. You can see that execution has stopped at the breakpoint. From here, you can step through your routine, with full debugging capabilities. 3. Press F5.4. In the Output window, in the Show output from drop-down list, select Database

Output. You can see that the output from the user-defined function is displayed in the Output window, allowing you to fully test your managed routines without leaving Visual Studio .

Task 5: Accessing a User-Defined Function from a Windows Application1. Select the File | Add | New Project menu command.

2. When prompted to save the existing project, select the C:\data folder.3. In the Project Types pane, select Visual C# 4. In the Templates list, select Windows Application. 5. In the Name field, enter :"SqlServerProjectWinApp. In the Location field, enter

"C:\data".6. Click OK to dismiss the dialog box. 7. If the DataSource Fields window appears, you may close it. 8. From the Toolbox, drag a Button control to the design surface of Form1.

Note

If the Toolbox window isnt visible, select View | Toolbox to display it.

9. Double-click Button1.Trang 40

SQL Server 2008

Trng i Hc Bch Khoa H Ni

10. Scroll to the top of the code file, and enter the following Imports statement: using System.Data.SqlClient;11. In the Code Editor, type the following code within the Button1_Click event handler:

string connectionString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=AdventureWorks"; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("SELECT dbo.GetTodaysDate()", conn); Object result = cmd.ExecuteScalar(); DateTime d = (DateTime) result; MessageBox.Show(d.ToString()); } This code is very straightforward. It opens a connection to the database and executes a simple command to display todays date in a message box. Note that the code required to call a managed code user-defined function is the same as the code to call a T-SQL user-defined function. 12. In the Solution Explorer, right-click SqlServerProjectWinApp and select Set as StartUp Project.13. Select the Debug | Start menu command (or press F5). 14. Click Button1.

You can see that the user define function, implemented as managed code, is accessed from the client exactly like a user-defined function written using T-SQL. 15. Click OK.16. Close Form1. 17. Select the File | Close Solution menu command.

This exercise provided an introduction to working with Visual Studio and Microsoft SQL Server . You also learned how to create SQL Server projects and how to write user-defined functions with managed code. Exercise 2: Leveraging the .NET Framework in Database Development In this exercise, you will learn how to leverage the .NET Framework when doing database development. You will learn how to create a user-defined function that uses regular expressions to validate input. In the past, this would have been difficult to accomplish with only T-SQL. Validating data passed to a procedure or function is aTrang 41

SQL Server 2008

Trng i Hc Bch Khoa H Ni

common database operation, and this exercise shows how easily this task can be accomplished using managed code.

Task 1: Creating a User-Defined Function1. Select the File | New | Project menu command. 2. Create a new C# project, selecting the SQL Server Project template. 3. In the Name field, enter UserDefinedFunction.

4. In the Location field, enter C:\data.5. Click OK. 6. In the Add Database Reference dialog box, select the existing reference to the

AdventureWorks database.7. Click OK. 8. In the Solution Explorer, right-click UserDefinedFunction and select Add | New

Item from the context menu.9. In the Add New Item dialog, click User-Defined Function. 10. Click Add. 11. In the Code Editor, change the existing function declaration line to the following

code: public static bool IsValidPostcode(string Postcode) You will now create a user-defined function that validates a Postcode. Note that the function is decorated with a [SqlFunction] attribute. This tells the compiler that the function is a SQL Server user-defined function. 12. Delete the following two lines of code: // Put your code here return "Hello";13. Inside IsValidPostcode, type the following line of code:

return System.Text.RegularExpressions.Regex.IsMatch( Postcode, @"^\s*(\d{4})\s*$"); Regular expression support is just one area of additional functionality that the .NET Framework provides. In fact, as a database developer, you now will have access to literally thousands of pre-built classes that you can reuse in your database objects. 14. Select the File | Save All menu item to save the project. Save the project in the C:\data folder.

Task 2: Calling a User-Defined Function from a Windows ApplicationTrang 42

SQL Server 2008

Trng i Hc Bch Khoa H Ni

1. Select the File | Add | New Project menu command. 2. Ensure that Visual C# is still selected in the Project Types pane. 3. In the Templates list, select Windows Application.

You will now create a Windows Forms application that will test the IsValidPostcode user-defined function. 4. In the Name field, enter UserDefinedFunctionWinApp.5. In the Location field, enter "C:\data" 6. Click OK. 7. From the Toolbox, drag a TextBox control to the design surface of Form1.

The user will enter post codes into the TextBox control. 8. From the Toolbox, drag a Button control to the design surface of Form1.9. Double-click button1. 10. In the Code Editor, type the following code within the button1_Click procedure:

string connectionString = "Data Source=localhost;" + "Integrated Security=SSPI;" + "Initial Catalog=AdventureWorks"; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand( "SELECT dbo.IsValidPostcode(@Postcode)", conn); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@Postcode", SqlDbType.VarChar); cmd.Parameters["@Postcode"].Value = textBox1.Text; Object result = cmd.ExecuteScalar(); MessageBox.Show(result.ToString()); } This code opens a connection to the database, and executes a simple command to call the user-defined function, passing in a value submitted by the user. This value will then be compared to a regular expression to insure that it is a properly formatted post code. 11. In the Code Editor, at the top of Form1.cs, type the following line of code:

Trang 43

SQL Server 2008

Trng i Hc Bch Khoa H Ni

using System.Data.SqlClient;12. In the Solution Explorer, right-click UserDefinedFunctionWinApp and select Set

as StartUp Project.13. Select the File | Save All menu command. 14. Select the Debug | Start menu command (or press F5). 15. In the text box enter 555-5555.

To test IsValidPostcode, you will first enter data that is invalid. 16. Click Button1. The application calls the user-defined function and displays a message box indicating that the data is not a valid postcode. 17. Click OK.18. In the text box, enter 1234. 19. Click button1.

Because 1234 is a valid post code, the code displays True.20. Click OK. 21. Close Form1. 22. Select the File | Close Solution menu command.

In this exercise, you learned how to create a user-defined function in managed code using Visual Studio . By leveraging the Base Class Library in the .NET Framework, you saw how you can use managed code to create powerful database objects. Exercise 3: Understanding Managed Code Permissions In this exercise, you will understand how different permission sets can be applied to assemblies running in Microsoft SQL Server . You will create a stored procedure that uses the .NET Framework to write to an external file. By default, managed code within Microsoft SQL Server is constrained so that it cannot access external resources. Therefore, appropriate permission must be granted to the assembly in order for it to write to the file. You will also learn how to load and unload assemblies manually using DDL statements within SQL Server Management Studio.

Task 1: Creating a Stored Procedure that Writes to a File1. Select the File | New | Project menu command.

2. Using C#, create a new SQL Server project..3. In the Name field, enter Permissions. 4. In the Location field, enter C:\data 5. Click OK.Trang 44

SQL Server 2008

Trng i Hc Bch Khoa H Ni

6. In the Add Database Reference dialog box, select the existing reference to the

AdventureWorks database.7. Click OK. 8. In the Solution Explorer, right-click Permissions and select Add | New Item from

the context menu.9. In the Add New Item dialog box, select Stored Procedure. 10. Click Add. 11. In the Code Editor, change the existing subroutine declaration line to the following:

public static void WriteToFile( string fileName, string message) Note Note: Be careful to not delete the SqlProcedure attribute preceding the declaration.

You will now create the body of the stored procedure that writes to the file. The procedure accepts two parameters: the file to write to, and the text to write. 12. Inside the WriteToFile subroutine, type the following lines of code: using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, true)) { sw.WriteLine(message); } This routine leverages the inherent functionality present in the .NET Base Class Library to write to the file. 13. In the Solution Explorer, right-click Permissions and select Build. 14. Select the File | Save All menu item, and save the project.

Task 2: Introducing SQL Server Management StudioFor this exercise, you will use SQL Server Management Studio to load the assembly. This will give you an opportunity to see how to load and unload assemblies manually using DDL statements. 1. From the Windows Task Bar, navigate to Start | All Programs | Microsoft SQL Server | SQL Server Management Studio.2. When prompted to connect, ensure that the Server type value is set to SQL

Server, the Server name is set to localhost, and Authentication is set to Windows Authentication. Click Connect. Microsoft SQL Server introduces a brand new tool for database management named SQL Server Management Studio. This serves as a replacement for EnterpriseTrang 45

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Manager and the Query Analyzer. 3. Select the View | Registered Servers menu command to ensure that the Registered Servers window is visible. The Registered Servers window displays all the SQL Servers that have been registered. 4. Select the View | Object Explorer menu command to ensure that the Object Explorer window is visible. The Object Explorer window displays various objects for a particular server. Specifically, it will show databases and their associated diagrams, tables, views, stored procedures, triggers, types, etc.

Task 3: Registering a Server in SQL Server Management Studio1. In Registered Servers, right-click Microsoft SQL Servers and select New |

Server Registration.2. In the Server instance field, enter localhost. 3. In the Authentication drop-down list, ensure that Windows Authentication is

selected.4. Click Test.

After a few seconds, a message box displays indicating the connection has been successful. 5. Click OK.6. Click Save. 7. In Registered Servers, double-click localhost. 8. In the Object Explorer window, expand localhost | Databases |

AdventureWorks.9. On the toolbar, click New Query, and then select New SQL Server Query.

Microsoft SQL Server displays the Connect to SQL Server dialog box. 10. In the Server instance field, enter localhost.11. Ensure that the Authentication drop-down list has Windows Authentication

selected.12. Click Connect.

13. In the query window, type the following line of code: USE AdventureWorks14. Press F5.

Task 4: Loading an Assembly Manually using DDL Statements1. Type the following lines of code into the query window:Trang 46

SQL Server 2008

Trng i Hc Bch Khoa H Ni

CREATE ASSEMBLY Permissions FROM 'C:\data\Permissions\Permissions\bin\Permissions.dll'

Make sure that there are no line breaks in the folder name when typing the Note code. 2. Select the above lines of code.3. Press F5.

Running this DDL statement loads the Permissions.dll assembly into Microsoft SQL Server . Up until now, you have been using Visual Studio to deploy all assemblies. This exercise demonstrates how to load an assembly manually using DDL for two reasons. First, loading the assembly automatically doesnt allow you to configure the permissions for an assembly, and the ability to configure a permission set will be needed later in the exercise. Second, this gives you a great opportunity to see what is going on under the covers. 4. Type the following lines of code: CREATE PROCEDURE WriteToFile @FILENAME NVARCHAR(256), @MESSAGE NVARCHAR(4000) AS EXTERNAL NAME Permissions.[StoredProcedures].WriteToFile 5. Select the above lines of code.6. Press F5.

Running this DDL statement will create an entry point for the managed stored procedure in the assembly you just loaded. 7. Type the following line of code: EXEC WriteToFile 'c:\test.txt', 'This is a test' 8. Select the above line of code.9. Press F5.

Running this T-SQL will cause an error indicating that you don't have permission to write to the file you specified, with text looking something like this (the actual text may be slightly different):

Trang 47

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Msg 6522, Level 16, State 1, Procedure WriteToFile, Line 0 A .NET Framework error occurred during execution of user defined routine or aggregate 'WriteToFile': System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. System.Security.SecurityException: at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path, Boolean append) at StoredProcedures.WriteToFile(String fileName, String message)

This error is expected. To ensure the security of the server, Microsoft SQL Server only grants a limited set of permissions to an assembly. The file is a secured resource and by default a stored procedure is not allowed to access secured resources. If an assembly needs additional permissions, it must be specifically granted.

Task 5: Unloading an Assembly and Stored Procedure Manually Using DDLStatements 1. Type the following two lines of code: DROP PROCEDURE WriteToFile DROP ASSEMBLY Permissions 2. Select the above lines of code.3. Press F5.

This will unload the stored procedure and assembly.

Task 6: Loading an Assembly with a Specific Permission Set1. Type the following lines of code:

Trang 48

SQL Server 2008

Trng i Hc Bch Khoa H Ni

ALTER DATABASE AdventureWorks SET TRUSTWORTHY ON CREATE ASSEMBLY Permissions FROM 'C:\data\Permissions\Permissions\bin\Permissions.dll' WITH PERMISSION_SET = EXTERNAL_ACCESS

Make sure that there are no line breaks in the folder name when typing the Note code. An important distinction between this CREATE ASSEMBLY statement and the previous one is that this time youre specifying the permission set to be used by the assembly. There are three different permission sets: SAFE, EXTERNAL_ACCESS, and UNSAFE. SAFE is the default permission set and works for the majority of scenarios. When code in an assembly runs under the SAFE permission set, it can only do computation and data access within the server via the in-process managed provider. EXTERNAL_ACCESS is a code permission set that addresses scenarios where the code needs to access resources outside the server such as the files, network, registry and environment variables. UNSAFE code permission is for those situations where an assembly is not verifiably safe or requires additional access to restricted resources, such as the Win32 API. 2. Highlight the above lines of code so that they are selected.3. Press F5.

Running this DDL statement loads the Permissions.dll assembly into Microsoft SQL Server with the EXTERNAL_ACCESS permission set. 4. Type the following lines of code again (or highlight the ones you had typed previously): CREATE PROCEDURE WriteToFile @FILENAME NVARCHAR(256), @MESSAGE NVARCHAR(4000) AS EXTERNAL NAME [Permissions].[StoredProcedures].WriteToFile 5. Select the above lines of code.6. Press F5.

7. Type the following line of code:

Trang 49

SQL Server 2008

Trng i Hc Bch Khoa H Ni

EXEC WriteToFile 'c:\test.txt', 'This is a test' 8. Highlight the above line of code so that it is selected.9. Press F5.

This time, the command is completed successfully. 10. In SQL Server Management Studio, select the File | Exit menu command. If prompted to save your changes, click No.

Task 7: Viewing the File1. Open Windows Explorer and find the file you just created.

2. Double-click the file to load it into NotePad. You can see that the message was written from the managed code into this file. 3. Close Notepad. In this exercise, you began working with SQL Server Management Studio, part of Microsoft SQL Server . You learned that .NET assemblies are loaded into Microsoft SQL Server using a giver permission set. By default, assemblies are loaded with limited privileges and cannot access external resources such files. To give an assembly access to external resources, it must be loaded with a different additional permission set such as EXTERNAL_ACCESS. You also learned how to manually load and unload assemblies and stored procedures using DDL. Exercise 4: Creating User-Defined Aggregates In this exercise, you will learn how to extend the list of installed aggregate functions by creating new user-defined aggregates whose implementation is in managed code.

Task 1: Testing the User-Defined Aggregate TemplateAn aggregate function performs a calculation on a set of values and returns a single value. T-SQL already comes with several built-in aggregate functions such as COUNT, AVG and SUM. With CLR integration, you will now be able to create your own aggregates using managed code. For this exercise, you will create a user-defined aggregate that performs string concatenation. 1. In Visual Studio , select the File | New | Project menu command.2. Create a new C# project, using the SQL Server Project template. 3. In the Name field, enter UserDefinedAggregates. 4. In the Location field, enter "C:\data". 5. Click OK. 6. In the Add Database Reference dialog box, select the existing reference to the

AdventureWorks database.7. Click OK.Trang 50

SQL Server 2008

Trng i Hc Bch Khoa H Ni

8. In the Solution Explorer, right-click UserDefinedAggregates and select Add |

New Item.9. In the Add New Item dialog box, click Aggregate.

10. Type UTSConcatenate as the name11. Click Add. 12. In the Code Editor, at the top of the code window, type the following code:

using System.Text; The aggregate you are creating will be using the StringBuilder class of the System.Text namespace. Importing System.Text will reduce typing. 13. Above the struct declaration, just below the serialization flag, you must indicate that you will be performing the serialization yourself. To do this, add the following attribute to the struct [SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize = 8000)] You must also implement the IBinarySerialize interface so SQL knows how to retain the values in the Stringbuilder within the struct public struct UTSConcatenate : IBinarySerialize14. In the UTSConcatenate class, before public void Init(), type the following code:

private StringBuilder sb; private bool firstConcat ; The StringBuilder object sb will be used to perform fast string concatenations. The Boolean flag firstConcat indicates whether a concatenation is the first concatenation. 15. In the Init procedure, before the closing bracket, type the following code: sb = new StringBuilder(); firstConcat = true; This will initialize the StringBuilder object when the aggregate is invoked. 16. In the Accumulate procedure, before closing bracket, type the following code:

Trang 51

SQL Server 2008

Trng i Hc Bch Khoa H Ni

public void Accumulate(SqlString value) { if (firstConcat) { sb.Append(value); firstConcat = false; } else { sb.Append(","); sb.Append(value); } } These lines of code perform the actual string concatenation. Accumulate is called for each row in the result set from which values will be aggregated. 17. In the Merge procedure, before the closing bracket, type the following code: Accumulate(Group.sb.ToString()); The Merge method is used by the query processor to merge another instance of this aggregate class with another instance as part of partial computations. 18. In the Terminate procedure, delete the following lines of code: Put your code here return new SqlString("");19. In the Terminate() routine, before the closing bracket, type the following code:

return sb.ToString(); This line of code converts the StringBuilder object to a regular String object and returns that String back to the calling code. Terminate is invoked when the entire result set has been processed. 20. As the final step, we will need to add a Read and Write procedure required by the IBinarySerialize interface. This is used to Serialize and De-Serialize the StringBuilder object so that it can be passed as a parameter into the Merge procedure. Add the following procedures to the class before the closing bracket.

Trang 52

SQL Server 2008

Trng i Hc Bch Khoa H Ni

public void Read(System.IO.BinaryReader r) { sb = new StringBuilder(r.ReadString()); } public void Write(System.IO.BinaryWriter w) { w.Write(sb.ToString()); } The completed UTSConcatenate class should now look like the following: using System; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Text; [Serializable] [SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize = 8000)] public struct UTSConcatenate : IBinarySerialize { private StringBuilder sb; private bool firstConcat ; public void Init() { sb = new StringBuilder(); firstConcat = true; } public void Accumulate(SqlString value) { if (firstConcat) { sb.Append(value); firstConcat = false; } else { sb.Append(","); sb.Append(value); } }

Trang 53

SQL Server 2008

Trng i Hc Bch Khoa H Ni

public void Merge(UTSConcatenate Group) { Accumulate(Group.sb.ToString()); } public SqlString Terminate() { return sb.ToString(); } public void Read(System.IO.BinaryReader r) { sb = new StringBuilder(r.ReadString()); } public void Write(System.IO.BinaryWriter w) { w.Write(sb.ToString()); } }21. In the Solution Explorer, right-click UserDefinedAggregates and select Rebuild.

Task 4: Deploying a User-Defined Function1. Switch to SQL Server Management Studio.

2. Switch to Visual Studio .3. In the Solution Explorer, right-click UserDefinedAggregates, and select Deploy.

Task 5: Testing the User-Defined Aggregate1. In Microsoft SQL Server Management Studio, in the existing query, type the following lines of code: SELECT dbo.UTSConcatenate(Name) FROM production.location 2. Select the above lines of code.3. Press F5.

The results should be:

Trang 54

SQL Server 2008

Trng i Hc Bch Khoa H Ni

Debur and Polish,Final Assembly,Finished Goods Storage,Frame Forming,Frame Welding,Metal Storage,Miscellaneous Storage,Paint,Paint Shop,Paint Storage,Sheet Metal Racks,Specialized Paint,Subassembly,Tool Crib4. Select the File | Exit menu command. If prompted to save changes, click No. 5. In Visual Studio , select the File | Close Solution menu command.

This exercise demonstrated how to create a user-defined aggregate using managed code. Lab Summary This lab showed you how Microsoft SQL Server and Visual Studio combine to provide a new level of power and flexibility when developing database and datacentric applications. You learned that the .NET Common Language Runtime is now hosted in Microsoft SQL Server so that you can stored procedures, user-defined functions and aggregates using managed code with languages such as Visual Basic .NET and Visual C#. Although managed code does not replace T-SQL, the ability to use managed code is an important new tool in the database developer's toolbox.

Trang 55