1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P3 doc

50 460 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 618,37 KB

Nội dung

DROP VIEW vewEmailContacts GO --Create view to select all columns for --all rows from the EmailContacts table. CREATE VIEW vewEmailContacts AS SELECT * FROM EmailContacts GO --Select all columns for all rows from --the vewEmailContacts view. SELECT * FROM vewEmailContacts Cont ra sting Un e n cr ypt ed and Encrypt ed View s Wit h m inor ext ensions, the preceding sam ple can serve as a t em plat e for t he creat ion of any view. The following script illust rat es one of t hese ext ensions. I t creat es a view in t he Chapt er04 dat abase t hat has t he Shippers t able in the Nort hwind dat abase as it s base t able. While t he row source for a view can reside in anot her dat abase, t he CREATE VI EW st at em ent can creat e a view only in t he current dat abase. Sim ilarly, t he DROP VI EW st at em ent can rem ove a view only from t he current dat abase. An easy way t o r eference a row source fr om anot her SQL Server dat abase is t o use a t hree- part nam e. The first part refers t o t he alt ernat e dat abase nam e, Nort hwind in t his case. The second part designat es t he owner of t he obj ect prov iding t he row source. When t he row source owner is t he default dbo user, you can om it it s explicit designat ion ( as in t he follow ing scr ipt ). The t hird nam e part denotes t he nam e of t he dat abase obj ect providing t he row source for a view . Figure 4- 1 shows t he resu lt set from t he SELECT st at em ent based on t he vewShippers view. Not ice t hat it m at ches t he values in t he Nort hwind Shippers table, which is the source for t he v ewShippers view. Not ice t hat unlike t he first code sam ple, t his one doesn’t include a specific reference t o t he Chapt er04 database. That ’s because Query Analyzer w ill cont inue to use Chapter04 unt il y ou specify a different dat abase wit h a new USE st at em ent . --CreatevewShippers --Search for, and remove if found, the --vewShippers view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vewShippers’) DROP VIEW vewShippers GO --Create a new version of the vewShippers --view in the Chapter04 database from the --Shippers table in the Northwind database. CREATE VIEW vewShippers AS SELECT * FROM Northwind Shippers GO --Select all rows and columns from the --vewShippers view in Chapter04. SELECT * FROM vewShippers Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figu re 4 - 1 . Th e resu lt set from a v ie w base d on t he Ship pe rs t able in t he N or t hw in d da t ab ase . The ENCRYPTI ON at t r ibut e isn’t set by default . Set t ing encrypt ion doesn’t change the result set from a SELECT st at em ent. I nst ead, it encodes t he T- SQL for a view ’s definit ion. You can verify t his by t r ying t o disp lay t he script for a view. The VI EW_DEFI NI TI ON colum n for t he I NFORMATI ON_SCHEMA.VI EWS view ret urns the script for a v iew on each of it s r ow s. The follow ing scr ipt dem onst rat es t he sy ntax for invoking t he ENCRYPTI ON at t ribut e. The scr ipt also dem onst rat es t he sy nt ax for ret urning t he script t hat defines a view . This script includes all com m ent s as well as t he operat ional T- SQL st at em ent s for cr eat ing t he v iew; t hese st at em ents include the CREATE VI EW st at em ent for generat ing a new v iew and t he SELECT st at em ent for defining a view ’s result set . I n t his case, t he SELECT st at em ent is ident ical t o t he one in t he preceding view . How ever, t he CREATE VI EW st at em ent includes t he WI TH ENCRYPTI ON clause t hat encodes t he T- SQL for t he view. After cr eat ing t he view, the script perfor m s a sim ple SELECT query t o v erify t he cont ent s of t he view ’s result set . Th e final port ion of t he script creat es anot her result set w ith t he definit ion for each user- defined view in t he current dat abase, which is Chapt er04 in t he sam ple. Om it t ing all row s beginning wit h “sys” for t heir TABLE_NAME colum n value in t he I NFORMATI ON_SCHEMA.VI EWS view excludes all syst em view s from the final result set . --CreatevewShippersEncrypted --Search for, and remove if found, the --vewShippersEncrypted view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vewShippersEncrypted’) DROP VIEW vewShippersEncrypted GO --Create a new version of the vewShippersEncrypted --view in the Chapter04 database from the --Shippers table in the Northwind database. CREATE VIEW vewShippersEncrypted WITH ENCRYPTION AS SELECT * FROM Northwind Shippers GO --Select all rows and columns from the --vewShippersEncrypted view in Chapter04. SELECT * FROM vewShippersEncrypted --List user-defined view names in Chapter04 database --along with their scripts. SELECT TABLE_NAME, VIEW_DEFINITION FROM INFORMATION_SCHEMA.VIEWS WHERE LEFT(TABLE_NAME,3) <> ’sys’ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 4- 2 sh ow s an excerpt from t he result set s for t he pr eceding script s. This excerpt is from t he Result s pane of Query Analy zer wit h a Result s To Grids set ting. The t op result set sh ows t he sam e t hree rows as in Figure 4-1. This confirm s that encrypt ing a view doesn ’t alt er t he resu lt from it s SELECT st at em ent . The second result set in Figure 4- 2 displays t he nam es of t he t hree view s cr eat ed t o t his point in t he chapt er. Next t o each view nam e is t he beginning of t he script for t he view. Because t he script s st art w it h com m ent s, t he VI EW_DEFI NI TI ON colum n values st art wit h t hese com m ents. Wit h a Result s To Text set t ing for t he Result s pane, you can exam ine t he w hole script for each view except vewSh ippersEncr ypted. The WI TH ENCRYPTI ON clause in t he CREATE VI EW st at em ent for t his view secures it s script so that t he VI EW_DEFI NI TI ON colum n of t he I NFORMATI ON_SCHEMA.VI EWS view cannot expose t he T- SQL t hat generat es t he view . Figu re 4 - 2 . An e xce r pt show ing th e resu lt set fr om a n e ncryp t ed view a s w e ll as t h e VI EW _ D EFI N I TI ON colum n va lu es from t h e I N FORM ATI ON _ SCH EM A.V I EW S vie w for t h re e view s in a dat abase . Sor t ing a n d Grouping W it hin a Vie w The SELECT st at em ent t hat def ines a view has generally t he sam e sy nt ax as t hat wit hin a st and- alone script. For exam ple, gr ouping rows t o aggr egat e a colum n value works t he sam e in both st and- alone script s and t hose inside view s. Sim ilarly, t he I N keyword in a WHERE clause works the sam e as well. I n cont rast , t he ORDER BY clause in a SELECT st at em ent requires slight ly different sy nt ax inside a view t han it does out side a view . I n part icular, ORDER BY inside a v iew requires the TOP predicat e aft er t he SELECT keyword. The TOP predicat e, in t urn, r equires an argum ent t o designat e how m any records t o ret ur n. I f you want all t he rows from a source, follow TOP wit h 100 PERCENT. You can designat e any ot her percent age as w ell as a num ber for any num ber of rows. Trailing TOP w it h t he num ber 10 w it hout t he PERCENT keyword ret urns the first 10 rows in t he result set . When you use an ORDER BY clause, t hose row s will be the highest or lowest colum n values on a sort dim ension depending on the sort order. The sy nt ax for designat ing a sort order in an ORDER BY clause is the sam e in a SELECT st at em ent in or out of a view . The follow ing scr ipt shows the cr eat ion and ret urn of values from a view t hat groups and sort s colum n values. The SELECT st at em ent for t he v iew also includes a crit er ion t hat filters exclusively for countries beginning wit h t he let t er B or C. Chapt er 3 included a sim ilar st and-alone script for count ing t he num ber of cust om ers by cit y wit hin count r y. Th e SELECT st at em ent in t he follow ing scr ipt is dist inct because of it s use of t he TOP predicat e. While t he TOP predicat e will w ork in a st and-alone script , it isn’t necessary. --CreatevewCustomersInCountryCity --Search for, and remove if found, the --vewCustomersInCountryCity view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vewCustomersInCountryCity’) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. DROP VIEW vewCustomersInCountryCity GO --Create a new version of the vewCustomersInCountryCity --view in the Chapter04 database. --To use ORDER BY clause in view you need TOP predicate --with modifier of 100 PERCENT. CREATE VIEW vewCustomersInCountryCity AS SELECT TOP 100 PERCENT Country, City, Count(CustomerID) ’# of Customers’ FROM Northwind Customers WHERE LEFT(Country,1) IN (‘B’,’C’) GROUP BY Country, City ORDER BY Country, City GO --Select all rows and columns from the --vewCustomersInCountryCity view in Chapter04. SELECT * FROM vewCustomersInCountryCity View s for Rem ot e a nd H et erogeneous Sources I t is oft en necessary t o view dat a r esiding on anot her SQL Server inst ance or even in anot her t ype of dat abase form at . T- SQL provides sever al appr oaches t o sat isfying t hese kinds of requirem ent s. The OPENROWSET funct ion is a flex ible approach because it can accom m odat e ad hoc queries as well as t hose perform ed on a regular basis. As m ent ioned prev iously, Books Online recom m ends t hat y ou use link ed ser vers when it is necessary t o query a rem ot e or het er ogeneous source on a regular basis. Howev er, you can invoke t he OPENROWSET funct ion for a userid t hat doesn’t have m em bership in t he sysadm in or set upadm in fixed server roles. The OPENROWSET funct ion depends only on t he perm issions for t he user id passed t o t he ot her dat a source. This sect ion present s a ser ies of OPENROWSET sam ples designed t o help you underst and rem ot e dat a access. Creat ing a View for Anot her SQL Ser ver I n st a nce One t ypical requirem ent is t o view a SQL Serv er row source, such as a t able, on anot her server. You can use t he OPENROWSET funct ion to perform t his task , wit h argum ent s t hat sp ecify a prov ider, ot her elem ents of a connect ion st ring, and a SELECT st at em ent . The OPENROWSET funct ion can serve as an argum ent for t he FROM clause of a SELECT st at em ent . This out er SELECT st at em ent , in t urn, m ust reside in a CREATE VI EW st at em ent w hen your goal is t o creat e a v iew in t he current dat abase t hat exposes a row source in anot her dat abase. When the inner SELECT st at em ent — t he one in t he call t o t he OPENROWSET funct ion— point s at anot her SQL Server inst ance, t he provider for t he funct ion should be SQLOLEDB. Next you can denot e t he rem aining elem ents of t he connect ion st ring for t he ot her server in t he follow ing order: t he ser ver inst ance nam e, a SQL Serv er login for t he server , and a passw ord for t he login. Follow t he prov ider nam e by a com m a, but use a sem icolon for a delim it er aft er t he server nam e and login nam e. A com m a separat es t he passw ord from t he SELECT st at em ent . The follow ing scr ipt cr eat es a view on one SQL Server running SQL Server 2000 that point s at a t able on t he cabxli ser ver running t he MSDE version com pat ible wit h SQL Server 7. You need t w o inst ances of SQL Server t o evaluat e t his scr ipt , Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. but you can nam e t he inst ances anyt hing you want. Just ch ange t he references to cabxli to t he nam e of a SQL Server inst ance t o which you can connect . By t he way, t he table is t he aut hors table in t he pubs dat abase; MSDE doesn’t rout inely inst all w it h t he pubs dat abase. Because cabx li is an int er nal t est serv er running Windows 98, t he serv er is available w it h sa and an em pt y password. Product ion servers should always have a password for t he sa login if you aren’t forcing Windows aut hent icat ion. The SELECT st at em ent refer ences t he aut hors t able in the pubs dat abase on t he cabxli server. The ORDER BY clause along wit h t he TOP predicat e sort s t he result set by aut hor first nam e w it hin aut hor last nam e. The out er SELECT st at em ent t akes t he OPENROWSET funct ion as t he argum ent for it s FROM clause. The SELECT list for t he outer SELECT st at em ent list s t he aut hors by first nam e, last nam e, and phone num ber, in t hat order. --CreatevewAuthorsSortedOnCabxli --Search for, and remove if found, the --vewAuthorsSortedOnCabxli view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vewAuthorsSortedOnCabxli’) DROP VIEW vewAuthorsSortedOnCabxli GO --Create a new version of the vewAuthorsSortedOnCabxli --view in the Chapter04 database from the --Shippers table in the Northwind database. CREATE VIEW vewAuthorsSortedOnCabxli AS SELECT au_fname, au_lname, phone FROM OPENROWSET(‘SQLOLEDB’,’cabxli’;’sa’;’’, ’SELECT TOP 100 PERCENT * FROM pubs authors ORDER BY au_lname, a u_fname’) GO --Select all rows and columns from the --vewAuthorsSortedOnCabxli view in Chapter04. SELECT * FROM vewAuthorsSortedOnCabxli GO Creat ing a View for an Acce ss Dat aba se I t isn’t uncom m on t o need t o upgrade Access applicat ions for t he use of an Access dat abase via a SQL Server solut ion. While you can perform a full-scale upsizing, it is possible t hat t he OPENROWSET funct ion can dram at ically reduce the effort of w orking w it h Access dat a from SQL Server. That ’s because t he funct ion perm it s a SQL Server solut ion t o view Access dat a wit hout t he need of transport ing t he dat a from Access t o SQL Server. Therefore, you save t he conversion effort . I n addit ion, your client s avoid the disrupt ion t hat could arise if their fam iliar Access solut ion were unavailable because you replaced it wit h a SQL Server applicat ion. At t he sam e t im e, new applicat ions can expose dat a from t he Access dat abase. So long as you don’t expect to exper ience bot t leneck s relat ed t o the capacit y of t he Access dat abase, this approach bears considerat ion. I n any event , the approach support s t he easy availabilit y of Access dat a from SQL Server views. You can use an OPENROWSET funct ion t o connect wit h an Access dat abase m uch like you use t he funct ion t o connect w it h a SQL Server dat abase on anot her SQL Server inst ance. The OPENROWSET funct ion is t he argum ent for t he FROM clause of a SELECT st at em ent . When connect ing t o an Access dat abase, you m ust specify t he Jet dat a provider followed by t he pat h t o t he Access database file, a login nam e, and a passw ord. Th e OPENROWSET funct ion also has it s ow n SELECT Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. st at em ent t hat specifies t he row source in t he Access dat abase as w ell as any special set t ings, such as a WHERE clause. The follow ing scr ipt dem onst rat es a connect ion to an Access dat abase file on the current com put er. The pat h points t o t he default inst allat ion of t he Nor t hw ind sam ple dat abase for Access 2002. The connect ion st ring specifies a login by t he adm in user wit h an em pt y password. This is norm al for an unsecured Access dat abase file, such as t he Access Nort hw ind sam ple. Th e SELECT st at em ent inside the OPENROWSET funct ion call designat es t he retur n of all rows wit h a Count ry colum n value of USA. When designat ing a st ring in t his inst ance, t he norm al synt ax is t o enclose t he st ring argum ent , USA, wit h a pair of single quot at ion m arks. How ever, w it hin the OPENROWSET funct ion, single quot at ion m arks are alr eady used around the SELECT st at em ent , so it ’s necessary t o use t wo single quot at ion m arks on each side of USA. I n t he following script , t he out er SELECT st at em ent disp lays all t he colum ns from the inner SELECT st at em ent . --CreatevewUSACustomersFromAccess --Search for, and remove if found, the --vewUSACustomersFromAccess view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vewUSACustomersFromAccess’) DROP VIEW vewUSACustomersFromAccess GO --Create a new version of the vewUSACustomersFromAccess --view in the Chapter04 database from the Customers table --in the Access Northwind database. (You should install the --Northwind sample if it isn’t already installed. Also, you --may need to change the path to Northwind.) CREATE VIEW vewUSACustomersFromAccess AS SELECT * FROM OPENROWSET( ’Microsoft.Jet.OLEDB.4.0’, ’c:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb ’; ’admin’;’’, ’SELECT * FROM Customers WHERE Country=‘‘USA’’’) GO --Select all rows and columns from the --vewUSACustomersFromAccess view in Chapter04. SELECT * FROM vewUSACustomersFromAccess GO Creat ing a View for an OD BC Row Sou r ce View ing an ODBC dat a source m ay be t he ult im at e in flex ibilit y because ODBC drivers are available for so m any different t ypes of dat abases. I n addit ion, t he MSDASQL provider, which is inst alled w it h Micr osoft Dat a Access Com ponent s, offers a st andard int erface t o ODBC dat a sources. The OPENROWSET funct ion through it s SELECT st at em ent let s your applicat ions ch oose a specific row source wit hin a dat a source or even filt er a r ow source t o der ive a new cust om source for an applicat ion. Using t he OPENROWSET funct ion t o connect with a row source in an ODBC dat a source bears a st rong r esem blance t o using t he funct ion t o connect wit h SQL Server and Jet r ow sources. The m ain differences are in the connect ion st ring specificat ions. Fir st y ou m ust designat e t he MSDASQL provider inst ead of t he Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. SQLOLEDB or Jet provider. Second you specify connect ion st ring elem ent s t hat are appropr iat e for t he dat a source t o which y ou want t o connect . The follow ing scr ipt shows the sy nt ax for an applicat ion of t he OPENROWSET funct ion w it h t he MSDASQL prov ider for an ODBC dat a source. I n fact , t he sam ple connect s t o a SQL Server dat a source wit h t he ODBC dr iver, but t he general synt ax issues are t he sam e as for any dat a source. This sam ple requir es t wo inst ances of SQL Serv er . For exam ple, t he connect ion st r ing elem ent s point t o t he cab2000 server running a SQL Serv er dat abase. You can replace t he reference t o cab2000 wit h t he nam e of any ot her inst ance of SQL Serv er on y our net work. The user id and passw ord are, respect iv ely, sa and password. The inner SELECT st at em ent for t he OPENROWSET funct ion ch ooses all t he row s from t he Orders table in t he Nort hwind dat abase whose OrderDat e is in 1998. A WHERE clause and a DATEPART funct ion part icipat e in t he designat ion of an appropriat e cr it erion for t he SELECT st at em ent . The outer SELECT st at em ent ret urns all colum ns from the Orders t able. --Createvew1998OrdersOnCab2000 --Search for, and remove if found, the --vew1998OrdersOnCab2000 view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vew1998OrdersOnCab2000’) DROP VIEW vew1998OrdersOnCab2000 GO --Create a new version of the vew1998OrdersOnCab2000 --view in the Chapter04 database from the Orders table --in the Northwind database on the Cab2000 server. CREATE VIEW vew1998OrdersOnCab2000 AS SELECT * FROM OPENROWSET(‘MSDASQL’, ’DRIVER={SQL Server};SERVER=cab2000;UID=sa;PWD=password’, ’SELECT * FROM Northwind Orders WHERE DATEPART(yyyy, OrderDate) = 1998’) GO --Select all rows and columns from the --vew1998OrdersOnCab2000 view in Chapter04. SELECT * FROM vew1998OrdersOnCab2000 Joining Row Sour ces for a View The value of being able t o pr ocess rem ot e and het erogeneous dat a sources m ult iplies when you can j oin t wo row sources from different serv ers or different dat abases. There are at least t wo approaches t o t his t ask. The first one is t o creat e a SELECT st at em ent t hat cont ains a JOI N operat or. I n t his approach, each side of t he j oin has it s own explicit OPENROWSET funct ion. The ot her approach is to cr eat e t w o new views, each based on it s own OPENROWSET funct ion. Then y ou can cr eat e a new, t hird, view t hat j oins t he t wo views. Eit her appr oach em pow ers an applicat ion t o process concurrent ly row sour ces from differ ent dat abase servers in different dat abase form at s! The follow ing scr ipt shows the sy nt ax for t he first approach. Like several of t he previous OPENROWSET funct ion sam ples, t his one r equires t wo inst ances of SQL Server. The scr ipt j oins rows fr om t he Or ders t able in a SQL Server dat abase w it h rows from t he Cust om ers t able in an Access dat abase file. The OPENROWSET funct ion declarat ions follow t he synt ax of prev ious sam ples t hat used t he funct ions separately as t he source for a view . This scr ipt sam ple j oins t he Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Cust om ers r ows wit h the Or ders rows based on t heir Cust om erI D colum n values. An advant age of nest ing t he t wo OPENROWSET funct ions as t he argum ent for t he FROM clause of t he out er SELECT st at em ent is t hat your applicat ion doesn’t require separat e v iews for each row source obj ect t hat get s j oined. This saves your applicat ion from opening t he views. --CreatevewAccessCustomersCab2000Orders --Search for, and remove if found, the --vewAccessCustomersCab2000Orders view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vewAccessCustomersCab2000Orders’) DROP VIEW vewAccessCustomersCab2000Orders GO --Create the vewAccessCustomersCab2000Orders view --in the Chapter04 database from the --OPENROWSET of CustomersFromAccess and --OPENROWSET of 1998OrdersOnCab2000. CREATE VIEW vewAccessCustomersCab2000Orders AS SELECT TOP 100 PERCENT c.CompanyName, c.ContactName, c.Phone, o.OrderID, LEFT(o.OrderDate, 11) ’Order Date’ FROM OPENROWSET(‘Microsoft.Jet.OLEDB.4.0’, ’C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb ’; ’admin’;’’, ’SELECT * FROM Customers WHERE Country=‘‘USA’’’) AS c JOIN OPENROWSET(‘MSDASQL’, ’DRIVER={SQL Server};SERVER=cab2000;UID=sa;PWD=password’, ’SELECT * FROM Northwind.dbo.Orders WHERE DATEPART(yyyy, OrderDate) = 1998’) AS o ON c.CustomerID = o.CustomerID ORDER BY c.CompanyName, o.OrderID GO --Select all rows and columns from the --vewAccessCustomersCab2000Orders view in Chapter04. SELECT * FROM vewAccessCustomersCab2000Orders The next script shows t he sy nt ax for t he alt ernat ive approach t o j oining t wo het er ogeneous dat a sources. Again, y ou need t wo SQL Server inst ances t o run the sam ple. Th is alt ernat ive j oins t wo pr eviously creat ed v iews. I n this inst ance, each view is from a prior sam ple in t his chapt er. I n addit ion, t he t wo views corr espond t o t he SELECT st at em ent s for each of t he nest ed OPENROWSET funct ions in the prior sam ple. Therefore, t he result is ident ical for t he next scr ipt and t he prior scr ipt . Howev er, t he code for t he next scr ipt is dram at ically sim pler. By segm ent ing t he t wo OPENROWSET funct ions int o separat e views, t he second approach m ak es it easier t o debug t he synt ax . On t he ot her hand, wit h t his approach your applicat ion requires the addit ional overhead of m anaging t wo separat e views. This includes cr eat ing, m aint aining, and opening t he v iew s. --Createvew2JoinedViews --Search for, and remove if found, the --vew2JoinedViews view in the Chapter04 database. IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = ’vew2JoinedViews’) DROP VIEW vew2JoinedViews GO Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. --Create a new version of the vew2JoinedViews --view in the Chapter04 database from --two other previously existing views. CREATE VIEW vew2JoinedViews AS Select TOP 100 PERCENT c.CompanyName, c.ContactName, c.Phone, o.OrderID, LEFT(o.OrderDate, 11) ’Order Date’ FROM vewUSACustomersFromAccess c JOIN vew1998OrdersOnCab2000 o ON (c.CustomerID = o.CustomerID) ORDER BY c.CompanyName, o.OrderID GO --Select all rows and columns from the --vew2JoinedViews view in Chapter04. SELECT * FROM vew2JoinedViews GO I nt roduct ion t o St ored Procedur es Stor ed pr ocedures are com piled bat ches of T- SQL st at em ent s. The bat ch of st at em ent s can cont ain near ly all t he T- SQL st at em ent t ypes. While a st ored procedure can r et urn a resu lt set t he sam e way a v iew does, st ored pr ocedures are m ore pow erful in several respect s. A view is a virt ual t able; a st or ed procedure is m or e like a procedure in Visual Basic. You can pass it param et ers, and it can ret urn values through it s result set , out put param et ers, and ret urn st at us values. I n fact , st ored procedur es can ret urn m ult iple result set s, while view s are lim it ed t o a single result sim ilar t o a t able. Uses for St or ed Pr ocedu r es Stor ed pr ocedures have four m ain uses. First , t hey can r et urn one or m or e result set s. You can program a st ored procedure t o ret urn m ult iple result set s as easily as including m ult iple SELECT st at em ent s w it hin a single st ored procedure. Anot her way st ored pr ocedures can ret urn r esult set s is via out put param et ers. An output param et er is a scalar value. A scalar value is a single value, such as a st ring or an int eger, t hat isn ’t a part of a rowset . While a result set can cont ain a scalar value, resu lt set s norm ally cont ain set s of values. Out put param et ers prov ide an efficient m eans for st ored pr ocedures to r et urn scalar values. St ored procedures can also ret ur n int eger values t hat indicat e how a st ored pr ocedure term inat es. SQL Serv er docum ent at ion refers to t hese ret ur n values as ret ur n st at us values. When a st ored procedure can follow any of several int er nal processing pat hs, ret urn st at us values can indicat e t o a calling rout ine which pat h a st ored pr ocedure pursued. A second m aj or use of st ored procedures is t he processing of input param et ers. These param et ers enable your applicat ions t o cont rol dynam ically t he t hings t hat a st ored pr ocedure ret urns. Not all T- SQL st at em ent s take param et ers. I n t hese circum st ances, you can com bine the use of param et ers wit h cont rol- of-flow st at em ent s, such as I F…ELSE st at em ent s, t o det erm ine what a st or ed procedure ret ur ns. One com m on use for param et ers is in t he WHERE clause of SELECT st at em ent s. By using input param et er values as cr it erion values for WHERE clause expr essions, your applications can dy nam ically control a st ored procedure’s result set . When users set t he par am et er values, you enable users t o cont rol an applicat ion dynam ically at run t im e. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. A t hird m aj or use for st ored procedur es is t he m anagem ent of insert / updat e/ delet e operat ions for row sources. I n t his cont ext , a st ored procedure prov ides value t o an applicat ion w it hout r et urning a r esult set , a param et er value, or a return st at us value. The procedure sim ply m odifies a row source. Because st ored procedures can set param et ers based on user input and the procedures can use param et ers for insert / update/ delet e operat ions, users can cont rol t he m odificat ions to a row source at run t im e. Fourt h, you w ill learn how t o use st ored procedures as program s im plem ent ed wit h a bat ch of T- SQL st at em ent s. This fourt h use under lies and ext ends t he ot her t hree uses for st ored procedures. These st at em ent s can include SELECT st at em ent s, ot her st at em ent s for insert / updat e/ delet e operat ions, and cont rol- of- flow st at em ent s, such as I F…ELSE st at em ent s. I n addit ion, you can sp ecify any of four t ypes of values— local variables, global variables, param et ers, and ret ur n st at us values— t o cont rol t he dy nam ic behav ior of a st ored procedure and how it com m unicat es wit h it s calling procedure. N ot e See the “Control- of-Flow” t opic in Book s Online for a good st ar t ing point that helps you to learn about t radit ional program m ing techniques for st or ed procedures. Anot her especially useful Books Online topic for learning about st ored procedure pr ogram m ing is “Pr ogram m ing St ored Procedures.” Re u sing T- SQL St a t em ent s w it h St ored Pr oce dure s One of t he m aj or advant ages of st ored procedures is that t hey can package T- SQL st at em ent s for r euse. Four T- SQL st at em ent s help you m anage t hese blocks of code. Two st at em ent s, CREATE PROCEDURE and ALTER PROCEDURE, enable the definit ion and refinem ent of the code wit hin a st ored procedure. Wit h t he DROP PROCEDURE st at em ent, you can rem ove a st or ed pr ocedure from a dat abase. The EXECUTE st at em ent perm it s you t o run a st ored procedure. The CREATE PROCEDURE st at em ent let s you creat e a st ored procedure. You can abbreviat e t his st at em ent as CREATE PROC. Follow t he st at em ent nam e wit h t he nam e for your st ored pr ocedure. SQL Server has a rich collect ion of syst em st ored procedures, which t ypically st art wit h sp_. Chapt er 2 includes exam ples of how t o use syst em st or ed pr ocedures w it h t ables. Syst em st ored procedures are available for m anaging every aspect of SQL Ser ver perform ance and adm inist rat ion. To avoid conflict s wit h syst em st ored procedures, avoid st art ing your own user-defined st or ed procedures w it h t he sp_ prefix. Th is chapt er uses udp as a prefix for user -defined st ored procedur es. Lik e view nam es, st or ed procedures should follow t he st andard rules for SQL Server ident ifiers. The CREATE PROC st at em ent s typically hav e t hree or four m ain elem ent s. First , CREATE PROC declares t he st ored procedure and assigns a nam e t o it . Second, you can specify one or m ore param et ers for t he procedure. The param et er declarat ions ar e opt ional. Third, t he AS keyword serves as a t ransit ional w ord bet ween t he declarat ion elem ent s and t he T- SQL code ( t he fourt h elem ent ) t hat enables a st ored procedure t o perform a t ask . The follow ing t em plat e illust rat es how t o arrange t hese st ored procedur e elem ent s. CREATE PROC procedurename Parameter specifications AS Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... and st and- alone T- SQL st at em ent s For exam ple, y ou can quer y I NFORMATI ON_SCHEMA views t o uncov er infor m at ion about t he obj ect s in a dat abase An advant age of a st or ed pr ocedur e is t hat t he T- SQL it cont ains is com piled A st and- alone T- SQL st at em ent m ust be com piled befor e SQL Server can use it Therefore, t he st or ed procedur e can r un t he sam e T- SQL code... ak e it easy t o encapsulat e T- SQL st at em ent s for reuse Second, it is sim ple t o r eference scalar UDFs in T- SQL script s and ot her SQL Serv er obj ect s Three scalar funct ion sam ples in t his sect ion confir m how easy it is t o encapsulat e T- SQL expr essions in UDF funct ions The sect ion also highlight s ways of referencing scalar UDFs in different T- SQL cont ext s Cr e a t in g a... at t aching dat abase files t o a server and creat ing a new blank dat abase fr om w hich you can inv ok e t he script s This chapt er also refer ences t he SQL Ser ver Nort hwind dat abase This dat abase is inst alled w it h SQL Ser ver 2000 I n t r odu ct ion t o User - D e fin ed Fu n ct ion s A user- defined funct ion perm it s a dev eloper t o save a body of T- SQL code and t hen reuse it UDFs... t hen reuse it UDFs can ret ur n bot h scalar values and t ables I n fact , SQL Serv er 2000 int roduces a new dat a t ype, t able, for represent ing t he ret urn of a t able from a UDF Visual Basic developers w ill feel com fort able w it h UDFs because in m any ways t hey perform lik e funct ion pr ocedur es in Visual Basic You can pass UDF values t hrough par am et ers, and t hey r et urn a value—... SELECT OrderID, CAST((RequiredDate - ShippedDate) AS int) ’Days shipped after required date’, CustomerID FROM Northwind Orders WHERE (RequiredDate - ShippedDate) IS NOT NULL ORDER BY (RequiredDate - ShippedDate) GO Run proc to list seven orders with the shipped date farthest behind the required date EXEC udpLongestLateOrdersWithoutTop 7 GO Please purchase PDF Split-Merge on www.verypdf.com to remove... ShippedDate) AS int) ’Days shipped after required’, CustomerID FROM Northwind Orders WHERE (RequiredDate - ShippedDate) IS NOT NULL ORDER BY (RequiredDate - ShippedDate) GO Run proc to list orders with the shipped date farthest behind the required date with one of two TOP predicates EXEC udpLongestLateOrdersWithTop 7 GO Re t u r n ing X I t e m s w it h SET ROW COUN T The SET ROWCOUNT st at em ent provides... as argum ent s for cont r ol- of- flow st at em ent s t o cont r ol t he operat ion of a st ored procedur e Local var iables can w or k in coordinat ion wit h param et ers by accept ing values fr om param et ers and passing values t o t hem Dev elopers fam iliar w it h SQL Serv er v ersions pr ior t o 7.0 m ay be fam iliar wit h t he t erm global var iables SQL Ser ver 2000 r efers t o t hese global... remove this watermark Cha pt e r 5 Pr ogr a m m ing Use r - D e fine d Fun ct ions a nd Tr igge r s This chapt er com plet es t he book’s review of dat abase obj ect s t hat facilit at e t he reuse of T- SQL code The beginning of t he chapt er int roduces user - defined funct ions ( UDFs) Your applicat ions can apply UDFs as if t hey wer e built - in funct ions The chapt er ex plor es t he different... user - defined st ored pr ocedur e The last row includes t he nam e and creat ion dat e for t he elevent h st or ed pr ocedur e The second r esult set cont ains a num ber t hat is t he count of t he num ber of user - defined st ored pr ocedur es— 11 Figu r e 4 - 3 Th e re t u r n fr om a u ser - d e fin e d st or ed pr oced u r e t h a t spe cifie s t w o r esu lt se t s Please purchase PDF Split-Merge... CreateudpLongestLateOrdersWithTop Remove prior version of stored procedure IF EXISTS (SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark WHERE ROUTINE_TYPE = ’PROCEDURE’ AND ROUTINE_NAME = ’udpLongestLateOrdersWithTop’) DROP PROCEDURE udpLongestLateOrdersWithTop GO Create proc for itemizing late orders with one of two TOP predicates . table -- in the Northwind database on the Cab2000 server. CREATE VIEW vew1998OrdersOnCab2000 AS SELECT * FROM OPENROWSET(‘MSDASQL’, ’DRIVER= {SQL Server} ;SERVER= cab2000;UID=sa;PWD=password’,. ’vewAccessCustomersCab2000Orders’) DROP VIEW vewAccessCustomersCab2000Orders GO -- Create the vewAccessCustomersCab2000Orders view -- in the Chapter04 database from the -- OPENROWSET

Ngày đăng: 24/12/2013, 02:18

TỪ KHÓA LIÊN QUAN