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

50 565 0
Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P2 pdf

Đ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

inform ation about views as well as tables. Specify a TABLE_TYPE colum n value of VI EW in the WHERE clause for a SELECT st at em ent t o return only views. Wit h t he COLUMNS view of t he I NFORMATI ON_SCHEMA, you can ret urn inform at ion about colum ns in a dat abase. The t hird bat ch illust rat es t his app- lication. I t also r eveals a new sy nt ax for specifying t he database serving as the source for t he view. Not ice t hat t he specificat ion of t he view nam e has t hr ee parts. The first of t hese is t he dat abase nam e— Chapt er02. Designat ing a database nam e as t he first part rem ov es t he need to designat e a dat abase cont ext w it h a USE st at em ent . This is because no m at ter what dat abase cont ext the st at em ent execut es, it always ext ract s infor m at ion from t he dat abase— that is, the first part of t he I NFORMATI ON_SCHEMA view nam e. The second and t hird part s follow t he convent ion for t he preceding bat ches except for t he nam e of t he specific I NFORMATI ON_SCHEMA view ( COLUMNS) . The sam ple also includes a WHERE clause t o reference a part icular table— in particu lar, Em ailCont act s. Wit hout t he WHERE clause, t he T- SQL st at em ent in the bat ch will ret urn inform at ion for all t he colum ns w it hin t he Chapt er02 dat abase, including t hose from sy st em and user- defined t ables. The final bat ch shows t he I NFORMATI ON_SCHEMA syntax for r eporting about t he keys in a dat abase. These include t he prim ar y k eys, for eign k eys, and unique keys. The inform at ion is really about t he colum ns on w hich an applicat ion defines it s keys. As w it h t he pr eceding bat ch, t his sam ple restrict s t he result only t o keys for t he Em ailContact s table. --INFORMATION_SCHEMA_Samples --List databases on current server. USE master SELECT * FROM INFORMATION_SCHEMA.SCHEMATA GO --List user-defined tables in Chapter02 database. USE Chapter02 SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE NOT(SUBSTRING(TABLE_NAME,1,3) = ’sys’ OR SUBSTRING(TABLE_NAME,1,3) = ’dtp’) GO --List all columns in EmailContacts table. SELECT * FROM Chapter02.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ’EmailContacts’ GO --List data on columns constrained as keys in --the EmailContacts table. SELECT * FROM Chapter02.INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = ’EmailContacts’ GO Figure 2- 2 displays an excerpt from t he result set for t he preceding script . The ret ur n for each batch begins w it h a new set of colum n headers. The list of databases includes our user- defined database, Chapt er02, along wit h t he two SQL Ser ver sam ple databases, pubs and Nort hwind, as well as t he four syst em databases. The second header shows j ust one row for t he lone table in Chapt er02. The t hird header rows reveal t he nam es of the four colum ns wit hin the Em ailCont act s t able. This view provides m uch addit ional inform at ion about each colum n, such as it s nullabilit y, dat a t ype, and relat ed settings, including it s precision and scale if appropriat e. The row for t he last set of colum n headers provides inform at ion about t he lone key for t he Em ailCont act s t able. This is t he t able’s pr im ary key . Each key has a nam e, w hich appears in t he Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CONSTRAI NT_ NAME colum n. Because our synt ax for t he creat ion of t he t able didn’t specify a nam e for t he pr im ary key, t he last row of out put in Fig ure 2-2 shows t he syst em -generat ed nam e for t he table’s prim ary key in t he CONSTRAI NT_ NAME colum n. A subsequent sam ple in t he “ Script ing Keys and I ndexes” sect ion illust rat es t he sy nt ax for assigning a specific nam e to a prim ary key. Figure 2 - 2 . Sa m ple out pu t from a se t of four T- SQL ba tche s illust r at in g t he b eh avior of I NFORM ATI ON _ SCH EM A view s. I NFORMATI ON_ SCHEMA offers m any m ore v iews besides those illust rat ed in t he preceding four bat ches. For exam ple, you can gat her inform at ion about check const raint s for colum n values, t able const raints, st ored procedures, and user- defined funct ions. Refer t o t he “I nform at ion Schem a View” t opic in Books Online for an overv iew of t he I NFORMATI ON_SCHEMA views along wit h links defining t he result set for each t ype of view available. W ork ing w it h Colum n Da t a Type s The “Creat ing a Table” sect ion int roduced t he CREATE TABLE st at em ent sy nt ax and dem onst rated how t o declar e t ypical sy st em dat a t ypes such as int and nvarchar. Apply ing this fram ework w ill enable you to assign t he ot her dat a types to colum ns as well. I n spit e of t he sim plicit y of t he ov erall approach, t here are special issu es for som e data t ypes, and one dat a t ype hasn ’t been covered yet . This sect ion r eviews t hese issu es. Com p aring t im e st am p an d da tet im e Dat a Types Those w ho are m igrat ing t o SQL Server m ay be confused at first by t he tim e- st am p dat a t ype and w het her it has anyt hing t o do w it h datet im e dat a ( it doesn’t ). The rowversion alias for t im est am p act ually sum m arizes the purpose of Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. the t im est am p dat a t ype m ore precisely. This m ay be one reason why Micr osoft plans to use t he rowv ersion nam e m ore prom inent ly in t he fut ure. The following script cont rast s t he t im est am p and dat et im e dat a t ypes. The cont rast relies on t wo t ables, t 1 and t 2, each w it h t hree colum ns, col1, col2, and col3. The col1 colum n has an int dat a t ype and offers a value for program m at ically populat ing rows in each t able. The col2 and col3 colum ns populat e aut om at ically . The data t ype for col2 is dat et im e, but it has a DEFAULT const raint t hat assigns the current t im e aut om atically. Users and your applicat ion’s code can override t his default value. The t im est am p dat a t ype also autom at ically populates col3 in bot h t ables. However, for t his dat a t ype, only SQL Ser ver updates the value. This occurs wit h t he insert ion of a new row or t he revision of any value in an exist ing row. Aft er cr eat ing t he t1 and t 2 t ables, t he scr ipt does a couple of operations t o cont rast t im est am p and dat etim e dat a t ypes. The script insert s a record into each table w it h a delay of 1 second bet ween each insert ion. The WAI TFOR DELAY st at em ent act ually suspends t he operat ion of SQL Server for t he durat ion of it s argum ent . Therefore, t he insert ion for t able t2 can occur m ore t han 1 second aft er the insert ion for t able t 1 because SQL Server requires t im e t o perfor m the operat ion. After running a SELECT query t o show the colum n values in t ables t 1 and t 2, t he script next updat es t he value of col1 in t able t 2. Then it reruns t he SELECT quer y t o dem onst rate t he im pact of t he operat ion on the colum n values in t he sam ple. At t he sam ple’s conclusion, the scr ipt rem oves t he t1 and t 2 tables from t he Chapt er02 dat abase. --CompareTimestampToDatetime --Execute statements after USE from Chapter02 database. USE Chapter02 --Create two tables named t1 and t2. CREATE TABLE t1 ( col1 int, col2 datetime DEFAULT GETDATE(), col3 timestamp ) CREATE TABLE t2 ( col1 int, col2 datetime DEFAULT GETDATE(), col3 timestamp ) GO --Insert a row in tables t1 and t2 with --a one-second delay between tables. INSERT INTO t1 (col1) VALUES (1) WAITFOR DELAY ’00:00:01’ INSERT INTO t2 (col1) VALUES (1) GO --Run queries on tables t1 and t2. SELECT ’t1’ AS ’Table Name’, * FROM t1 SELECT ’t2’ AS ’Table Name’, * FROM t2 GO --Update column col1 in table t2. UPDATE t2 SET col1 = col1 + 2 GO --Re-run queries on tables t1 and t2. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. SELECT ’t1’ AS ’Table Name’, * FROM t1 SELECT ’t2’ AS ’Table Name’, * FROM t2 GO --Drop tables t1 and t2. DROP TABLE t1 DROP TABLE t2 GO Figure 2- 3 sh ows the Result s pane from Query Analyzer for t he preceding script. The col2 value for t he second row is 1 second plus a SQL Server clock t ick (3 m illiseconds) behind t he col2 value for t he first row. This clock t ick is the t im e that it takes t o com plet e t he row insert ion for t able t2. The col3 values for t he first and second rows are displaced by 1. Because the insert ion for t able t 2 occurred im m ediat ely aft er t he one for table t 1, t his is appropriat e. I f other insert ions t ook place bet ween t he init ial insert ion for table t1 and table t 2, the difference in t he binary value for col3 w ould be great er. Th e updat e of col1 for table t 2 dem onst rat es t his point . The second pair of rows in Fig ure 2- 3 also displays t he colum n values for tables t1 and t 2 after an updat e t o col1 in t able t 2. I n the case of t able t 1, t he col3 value rem ains unalt ered. However, t he col3 value for t able t2 grows by 1 from it s init ial value aft er t he insert ion. This incr eased value reflect s t he im pact of t he updat e to col1 in t able t 2. While t he second pair of rows varies from t he first pair for col3 in Figure 2- 3, t he col2 values are ident ical between t he first and second pair of rows. This is because updat ing values of ot her colum ns has no im pact on the dat et im e values in col2, but updating any value in a row does im pact t he value of t he t im est am p colum n value in t he row. N ot e You can have just one colum n per table with a t im est am p dat a t ype. Figure 2 - 3 . Sam ple out pu t contr ast ing t he beh avior of da tet im e an d t im e st am p da ta t ypes. Usin g sql_ v ariant D at a Typ e V alue s The sql_v ariant dat a type is the only dat a t ype t hat let s you st ore different data types in t he sam e colum n. This capability is useful for st oring a collect ion of values in a colum n in which you don’t know in advance what types of values you’ll Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. have. This can arise in a sit uat ion in which you let a user define values on an ad hoc basis. Consider a t able t hat st or es m iscellaneous inform at ion about cont act s. Som et im e your applicat ion m ay need t o st ore a m oney dat a t ype, anot her t im e a user m ay want t o specify a dat e, and in yet ot her cases, your application m ay need t o designat e a variable- lengt h charact er value. This kind of scenar io is t ypical of sit uat ions in which your application needs to charact erize elem ent s but t he com plet e set of elem ent s and their at t ribut es isn’t known at t he t im e t hat you develop t he applicat ion. The follow ing script assigns a set of ext ended propert ies t o a t able of cont act s ident ified by a Cont actI D colum n. Not ice t hat t he CREATE TABLE st at em ent uses t hr ee colum ns t o charact erize t he cont act s. The m ost im port ant colum n is PropValue, w hich has a sql_variant dat a t ype. This colum n st ores t he act ual value t hat charact erizes a cont act . I n som e cases, t he cont act charact er ist ic is a m onet ary value, in ot her cases it is a dat e, and in st ill ot her cases it is a st ring value, such as t he nam e of a favorit e sport or st ore. PropI D and PropNam e describe t he charact erist ic for t he cont act . PropNam e m ak es it easy t o follow what t he PropValue colum n values describe wit hout r equiring anot her t able t o decode t he PropI D colum n values. A subsequent sam ple w ill ret urn t o t he Cont act ExtProps table and link it t o ot her tables cont aining cont act and propert y nam es. I n addit ion, t hat sam ple w ill add a prim ary key t o t he t able. These refinem ent s aren’t necessary t o dem onst rat e t he behavior of sql_variant dat a t ypes. The I NSERT I NTO st at em ent s t hat add values to t he Pr opValue colum n use CAST funct ions to est ablish sub dat a t ypes w it hin t he sql_variant colum n. This isn’t st rict ly necessary, but t he CAST funct ion confir m s t he abilit y of t he sql_variant dat a t ype t o accept m ult iple ot her dat a t ypes. --SQL_variantSample --Execute statements after USE from Chapter02 database. USE Chapter02 GO --Remove prior version of ContactExtProps if it exists. IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ’ContactExtProps’ ) DROP TABLE ContactExtProps GO --Create ContactExtProps with four columns. CREATE TABLE ContactExtProps ( ContactID int NOT NULL, PropID int NOT NULL, PropName nvarchar(20), PropValue sql_variant ) GO --Populate ContactExtProps with values. INSERT INTO ContactExtProps VALUES(1, 1,’Birthday’, CAST(‘9/9/1944’ AS datetime)) INSERT INTO ContactExtProps VALUES(1, 2, ’Salary’, CAST(50000 AS money)) INSERT INTO ContactExtProps VALUES(1, 3, ’Bonus’, CAST(30000 AS money)) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. INSERT INTO ContactExtProps VALUES(1, 4, ’Favorite Sport’, ’Boxing’) INSERT INTO ContactExtProps VALUES(2, 1, ’Birthday’, CAST(‘1/1/1950’ AS datetime)) INSERT INTO ContactExtProps VALUES(2, 2, ’Salary’, CAST(60000 AS money)) INSERT INTO ContactExtProps VALUES(2, 3, ’Bonus’, CAST(40000 AS money)) INSERT INTO ContactExtProps VALUES(2, 5, ’Favorite Store’, CAST(‘Tailspin Toys’ AS nvarchar(2 0))) GO --Select all records with a Favorite Store property. SELECT ContactID, PropName, PropValue FROM ContactExtProps WHERE PropName = ’Favorite Store’ GO --Select Salary and Bonus properties and add one to --money data type for Salary and Bonus properties. SELECT ContactID, PropName, Cast(PropValue AS money)+1, PropValue FROM ContactExtProps WHERE PropID >=2 and PropID <=3 GO --This SELECT fails because sql_variant doesn’t implicitly --convert to other data types (for example, money) SELECT ContactID, PropName, Cast(PropValue AS money), PropValue+1 FROM ContactExtProps WHERE PropID >=2 and PropID <=3 GO Three SELECT queries at t he end of t he preceding script illust rat e som e of your options for extract ing dat a from colum ns declared w it h a sql_var iant data t ype. The first SELECT query includes PropValue, t he sql_var iant dat a t ype, in t he SELECT list for a query , but it uses a colum n defined wit h t he nvarchar dat a t ype in a WHERE clause. This SELECT query succeeds and ret urns t he nam e of t he favorite st ore for any record t hat has the PropNam e value ’Favorite St ore’. The second SELECT query uses PropI D, a colum n wit h an int data t ype, in t he WHERE clause t o extract records with inform ation about salary and bonus for cont act s in the PropValue colum n. Th is sam ple t ransf orm s t he sql_variant dat a type for PropValue t o a m oney dat a t ype in the SELECT list . Then it adds 1 t o t he transform ed value. This addit ion operat ion succeeds because it works wit h t he explicit ly convert ed sql_var iant data t ype. The last SELECT query tries t he sam e addit ion t ask as t he second SELECT query, but its SELECT list relies on an im plicit t ransform at ion of t he sql_variant dat a t ype to a dat a type t hat support s addit ion. Because SQL Server doesn’t support t his transform at ion for a sql_var iant source dat a t ype, t he last SELECT query fails. Figure 2- 4 displays t he out put from t he first two successful query st at em ent s. Figure 2 - 4 . Not ice t ha t t h e Pr opVa lu e colum n, w hich h as a sql_ va rian t data t ype, r et u rns values w it h diffe re nt data t ype form at s, su ch a s va ria ble-lengt h cha ra ct er st rin gs and m one y. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Usin g Com pu te d Colum n s in Table s A com put ed colum n adds a virt ual colum n t o a t able based on an expression t hat draws on one or m ore other colum ns wit hin the table. You can specify a com puted colum n wit h a CREATE TABLE (or an ALTER TABLE) st at em ent . You can use a com put ed colum n in a SELECT list , a WHERE clause, or an ORDER BY clause. I n addition, com puted colum ns can part icipat e in t he definition of an index or prim ary key. You can also use a com put ed colum n in t he definit ion of a UNI QUE const raint. When you’re using a com put ed colum n t o help define a prim ary key or an index, t he expression m ust be det erm inist ic. I n ot her words, the expression m ust generat e t he sam e result all t he tim e based on t he sam e input . An expression based on GETDATE isn’t appropriat e for a com put ed colum n that will serve as a colum n for an index. This is because t he result will change each t im e you open t he t able. Despit e the wide range of uses for com put ed colum ns, t here are sev eral circum st ances in which you cannot use t hem . For exam ple, you cannot sp ecify nullabilit y for com put ed colum ns. This is because SQL Ser ver autom at ically det erm ines w het her a com put ed colum n is null based on it s input and t he expression for com bining t he com put ed colum ns in quest ion. Even non- nullable input s can generat e null r esult s if an expression generat es an underflow or ov erflow. I n addition, you cannot specify input s or m odify t he cont ent s of colum ns w it h I NSERT I NTO or UPDATE st at em ents. Yet another applicat ion t hat doesn’t perm it t he use of com put ed colum ns is that which defines FOREI GN KEY and DEFAULT const raint s. The follow ing script sam ple illust rat es t he sy ntax for sp ecifying a com put ed colum n and shows an exam ple of how t o use it . The CREATE TABLE st at em ent designat es t hr ee colum ns for t he Proj ect edDeliveryDat es table. The first colum n is autoincr em ent ing, wit h default set tings for t he I DENTI TY colum n pr oper ty. The second colum n has a dat et im e dat a t ype for accept ing order dat es. The third colum n is a com put ed colum n. The expression for t he colum n uses the Dat eAdd funct ion to com pute a proj ect ed delivery dat e based on t he t able’s OrderDat e colum n. N ot e The I DENTI TY property perm its y ou to set t he seed value and t he st ep value for an aut oincrem enting series. I t s default seed and st ep values are both 1. You can specify alternat e seed and st ep values by adding parentheses aft er the keyword. For exam ple, use I DENTI TY(100, 10) t o specify a Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. series that st art s at 100 and progresses in steps of 10. --ComputedColumnSample --Execute statements after USE from Chapter02 database. USE Chapter02 GO --Remove prior version of ProjectedDeliveryDates if it exists. IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ’ProjectedDeliveryDates’ ) DROP TABLE ProjectedDeliveryDates --Create ProjectedDeliveryDates with three columns. CREATE TABLE ProjectedDeliveryDates ( OrderID int IDENTITY Not Null PRIMARY KEY, OrderDate datetime Not Null, ProjectedDeliveryDate AS DateAdd(day, 10, OrderDate) ) GO --Populate ProjectedDeliveryDates. INSERT INTO ProjectedDeliveryDates Values(GetDate()) INSERT INTO ProjectedDeliveryDates Values(‘9/1/01’) --Display date and time for projected delivery. SELECT OrderID, OrderDate, ProjectedDeliveryDate FROM ProjectedDeliveryDates --Display just date for projected delivery. SELECT OrderID, OrderDate, LEFT(ProjectedDeliveryDate,12) AS ’ProjectedDeliveryDate’ FROM ProjectedDeliveryDates GO Aft er insert ing order dat es based on eit her t he GETDATE funct ion or a st ring represent ing a dat e, t he script queries t he Proj ect edDeliveryDat es table wit h t wo separat e SELECT queries. The first SELECT query st at em ent dem onst rat es t he com puted colum n as part of t he list for t he st at em ent. For this st at em ent, t he Proj ect edDeliveryDat e colum n displays bot h t he dat e and t he t im e. However, your applicat ion m ay require j ust t he dat e. The second query stat em ent shows how t o cr op t he t im e value out of t he display. Figure 2- 5 present s the output from bot h SELECT st at em ent s. Figure 2 - 5 . Th is exam ple sh ow s t he u se of a com pu t ed colu m n to disp la y a pr oj ect e d d at e for t he de livery of an or de r in eit he r of t w o re pre se nt at ions—on e t ha t inclu des a t im e a nd an ot h er t h at show s on ly a date . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Adding Check Con st raint s Check const raints are am ong t he m ost sim ple of the const raint t ypes available t o database dev elopers and adm inist rators. Basically, a ch eck const raint allows you to r est rict the values entering a colum n— som ewhat in t he way t hat dat a type specificat ions do. (Users cannot ent er a charact er st ring into a colum n wit h an int data t ype.) However, check const raints base t heir rest rict ion on a Boolean expression t hat evaluat es t o Tr ue or False. The const raint expression can draw on one or m ore colum n values from t he t able to which it applies. A colum n const raint applies to an individual colum n, and a table const raint references two or m or e colum ns. The value False for t he expression violat es t he const raint . SQL Server rej ect s the insert ion of a r ecord wit h a value t hat violat es a const raint . You can use t his behavior t o m aint ain the int egrity of t he colum n values in t he t ables of your dat abase applicat ions. The follow ing script has three bat ches of st at em ent s. First the scr ipt adds a colum n check const raint t o t he Em ailCont act s t able init ially generat ed in the “Creating a Table” sect ion. The first bat ch also t est s the const raint by attem pt ing to insert a row wit h a colum n value t hat v iolat es t he const raint . I n t he second batch, the scr ipt shows how t o disable a const raint. Th is bat ch at t em pt s t o insert the sam e record t hat failed in t he first bat ch, but t his tim e t he insertion succeeds. The t hird bat ch dr ops t he const raint from t he Em ailCont acts t able and delet es t he record added in t he second bat ch. You can use t he ALTER TABLE st at em ent t o add a colum n check const raint t o a table, su ch as Em ailCont act s. The ALTER TABLE st at em ent perm it s the m odificat ion of a t able after its creat ion. Besides adding ch eck const raint s, you can add ot her const raint s, such as prim ary or for eign keys, and new colum ns. To add a const raint , use t he ADD k eyword followed by CONSTRAI NT. You can optionally assign a const raint nam e. Specifying a const raint nam e is par ticular ly convenient if your applicat ion has a need t o disable or rem ov e a const raint . I f you don’t explicit ly nam e your const raints, SQL Server aut om at ically assigns a nam e. The CHECK keyword specifies t he t ype of const raint. Finally, t he expression trailing t he CHECK keyw ord repr esents t he condit ion for which t he ch eck const raint t est s. I n t he sam ple script , t he const raint evaluat es t he Email1 value to ensure t hat it cont ains t he @ sy m bol. E-m ail addresses t hat don’t include t his sym bol are invalid. --ColumnCheckConstraintSample USE Chapter02 --Add CHECK constraint to require at --least one @ in Email1. ALTER TABLE EmailContacts ADD CONSTRAINT ch_EmailContacts_Email1_for@ CHECK (CHARINDEX(‘@’,Email1)<>0) --Test constraint with an Email1 value Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. --that contains no @; the INSERT statement fails. INSERT INTO EmailContacts VALUES (3,’Karl’, ’Doe1’, ’Doe1.hlcofvirginia.com’) GO --Disable the constraint. ALTER TABLE EmailContacts NOCHECK CONSTRAINT ch_EmailContacts_Email1_for@ --Test the disabled constraint with an Email1 value --that contains no @; the INSERT statement succeeds. INSERT INTO EmailContacts VALUES (3,’Karl’, ’Doe1’, ’Doe1.hlcofvirginia.com’) GO --Drop the constraint and delete bad Email1 row. ALTER TABLE EmailContacts DROP CONSTRAINT ch_EmailContacts_Email1_for@ DELETE FROM EmailContacts WHERE LastName = ’Doe1’ GO Scr ipt ing Keys and I n dex es This sect ion drills down on techniques for script ing prim ary keys, for eign keys, and indexes in your tables. Each t opic begins wit h a brief descr iption of background issues befor e t he discussion of a sam ple or t wo t hat illust rate t ypical uses for t he t opic. Prim a ry Keys Prim ar y keys have t wo especially dist inct ive feat ures. Fir st, each row m ust have a unique prim ary key value. Second, no prim ary key value can be null— even if it is the only null record in a t able. I t is com m on, but not m andat ory, t o base prim ary keys on a single colum n wit h an I DENTI TY propert y setting. A prim ary key can span m ult iple colum ns. Each pr im ar y key cr eat es an index. An index is a dat abase obj ect t hat support s fast access to the rows wit hin a t able or view. Any one SQL Serv er table can have up t o 250 index es, but only one of t hese can be clust ered. A clust ered index physically orders t he records for a t able in st orage according t o t he index values. Because a clust ered index can speed perform ance so m uch, you sh ould reserv e the clust ered index so t hat it serves your applicat ion’s m ost heav ily used lookup requir em ent . You can m ake eit her t he index for t he prim ary key or anot her index the clust ered index for a t able. Wit h a st andard SQL Server inst allat ion, a prim ary key declarat ion m ak es t he prim ary key clust ered by default . However, you can explicit ly declare a prim ary key as nonclust ered. As m ent ioned previously, t he prim ary k ey can have it s nam e assigned eit her by the sy st em or by a user . The follow ing script sam ple re-creat es t he Em ailCont act s table. I f you check t he sam ple in t hat sect ion, you w ill observe t hat the prim ary key declarat ion doesn’t include a nam e for t he prim ary key. The follow ing script re- creat es t he generat ion of t he Em ailCont act s table, but t his sam ple does explicit ly nam e t he prim ary key. The sam ple also dem onst rat es t he use of t he sp_pkeys syst em st ored procedure— once before dropping t he first version of the Em ailCont act s t able and a second t im e aft er creat ing a new version of the t able wit h a user- defined nam e for t he prim ary key. The sp_pkeys syst em st ored procedure has a result set w it h a separat e row for each colum n in t he prim ary Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Cha pt e r 3 Pr ogr a m m ing D a t a Acce ss w it h T- SQL This chapt er present s T- SQL program m ing t echniques for dat a access You can use t hese t echniques in m any env ironm ent s— in Query Analyzer , encapsulat ed wit hin v iews, in st or ed procedur es and user - defined funct ions— and in Visual Basic NET When... t akes t o run som e T- SQL st at em ent s Ot her, m ore com prehensiv e, per for m ance m easures are av ailable fr om SQL Serv er ; see, for exam ple, “Query Window St at ist ics Pane” in Books Online for m or e det ail N ot e Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark A local var iable in T- SQL oper at es like a m em ory var iable in Visual Basic Ch a pt e r 3 provides... fr om a SQL Serv er dat abase for any applicat ion The obj ect iv e of t his chapt er is t o dem y st ify T- SQL dat a access t echniques so t hat you can creat e T- SQL SELECT st at em ent s as easily as you used t o w rit e DAO and ADO dat a access code Alt hough t he chapt er assum es you’r e wor k ing in Query Analyzer, t he t echniques y ou lear n w ill apply equally w hen y ou use T- SQL st at... ss w it h T- SQL Creat ing efficient , speedy, and flex ible dat a access solut ions for SQL Ser ver dat a will inev it ably involve pr ogram m ing T- SQL I n part icular, you w ill r equir e a firm foundat ion in t he design of SELECT st at em ent s This sect ion int roduces t he SELECT st at em ent by review ing it s archit ect ur e You’ll find code sam ples designed t o illust rat e t he basic operat... Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Learning t he synt ax and clauses for t he SELECT st at em ent is t he surest way t o guarant ee your pr oduct ivit y w it h SQL Serv er As m ent ioned in t he int roduct ion t o t his chapt er , y ou can use t he SELECT st at em ent in SQL bat ches for Query Analyzer, v iews, st or ed procedur es, and user - defined funct... em ent for dat a access wit h SQL Serv er A SELECT st at em ent can generat e a set of v alues SQL Serv er lit erat ur e calls t he values r et urned by a SELECT st at em ent it s r esult set A t ypical SELECT st at em ent can r et ur n a scalar value, a single colum n of values, or a t w o- dim - ensional ar ray of values I n norm al dat a access scenarios, t he t wo- d- im ensional array of values... Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark in t he last r ow of Figure 2- 6 m at ches t he nam e assigned t o t he pr im ary key in t he preceding script Figu r e 2 - 6 Sa m ple ou t pu t de m on st ra t ing pr im a ry k e y n a m e s a ssig n e d by t h e syst e m ( t op r ow ) a n d by t h e pr ece d ing scr ip t ( bot t om row ) Recall t hat t he “Using sql_ var iant... he default m essage w it h t he SET Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark NOCOUNT ON st at em ent Then it declares a local st r ing var iable— @st r Rows—for it s cust om r eport about t he num ber of r ows r et ur ned The @@ROWCOUNT global variable r et urns t he num ber of r ecords affect ed by t he last T- SQL st at em ent Because t his funct ion ret ur ns... Return rows with Country values beginning with U SELECT CompanyName, Country FROM Customers WHERE Country LIKE ’U%’ By applying t he _ param et er in t he argum ent for a LI KE operat or, a SELECT st at em ent can r et urn j ust rows t hat cont ain USA inst ead of UK The ’U_A’ ar gum ent fails t o m at ch r ows wit h t he Count r y colum n value UK Please purchase PDF Split-Merge on www.verypdf.com to... pr ocedure or a t ablevalued user- defined funct ion The T- SQL sam ples for t his chapt er ar e available in an sql file on t he com panion disk You can use t he script s as st art ing point s for your own cust om ext rapolat ions of t he t echniques You can r un all t he sam ples fr om Query Analyzer if y ou have t he Nort hwind and pubs dat abases inst alled on a SQL Ser ver inst ance t o w hich . sysindexes. -- IndexSamples USE Chapter02 -- Create a stored procedure to list for user-defined -- tables object name from sysobjects, and name and -- indid from. (CHARINDEX(‘@’,Email1)<>0) -- Test constraint with an Email1 value Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. -- that contains no

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

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan