• Tidak ada hasil yang ditemukan

Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books

N/A
N/A
Protected

Academic year: 2017

Membagikan "Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books"

Copied!
22
0
0

Teks penuh

(1)

Creating Stored

Procedures with

SQL Server

I

n this c hapter, I’m go ing to sho w yo u ho w to build and debug sto red pro c edures using SQL Server. Sto red pro c edures are basic ally subro utines that yo u c an c all fro m yo ur pro -gram to perfo rm a database task. They are written in a language c alled Transac t-SQL, whic h is really just SQL with a few extra statements that help yo u test c o nditio ns and perfo rm lo o ps.

Introducing Stored Procedures

A sto re d pro ce dure is a c o llec tio n o f SQL statements that are sto red in the database server. These statements are sto red in bo th text fo rm and in c o mpiled fo rm fo r fast exec utio n. They c an be used in plac e o f an SQL statement o r c alled like a func -tio n o r subro utine.

The c o nc ept o f sto red pro c edures is c o mmo n to mo st database management systems o n the market to day, tho ugh the imple-mentatio ns are usually suffic iently different to make c o nverting sto red pro c edures fro m o ne vendo r to ano ther vendo r a diffi-c ult task. Yet sto red pro diffi-c edures diffi-c an make a big differendiffi-c e in the perfo rmanc e o f yo ur applic atio n so many pro grammers rely o n them fo r their applic atio ns.

Why use stored procedures?

Sto red pro c edures allo w yo u to c reate a blo c k o f c o de that c an be c alled fro m any database applic atio n o r database utility. This c o mmo n blo c k o f c o de has three primary advantages: per-fo rmanc e, c o nvenienc e, and sec urity. A sto red pro c edure usu-ally needs fewer reso urc es to run when c o mpared to a blo c k o f regular c o de, c o upled with c alls to the database server. A sto red pro c edure is easy to use, sinc e it typic ally represents

(2)

a c o mplic ated pro gramming o bjec t that c an be used as easily as a no rmal SQL state-ment. Sinc e a sto red pro c edure is sec ured just like any o ther database o bjec t, yo u c an also grant o thers the c apability to perfo rm a task that exc eeds their no rmal sec urity permissio ns.

Improving performance

The number o ne reaso n peo ple use sto red pro c edures is that they are usually mo re effic ient than explic itly inc luding the c o de in yo ur applic atio n pro gram. This is bec ause when yo u submit an SQL statement to the database server, the fo llo wing steps o c c ur eac h time an applic atio n pro gram attempts to perfo rm a task:

1.The applic atio n pro gram transmits the SQL statement to the database server o ver the netwo rk.

2.The datab ase server parses the SQL statement and then c o mpiles it fo r exe-c utio n.

3.The database server exec utes the c o mpiled statement.

4.The exec utio n’s results are returned o ver the netwo rk to the applic atio n pro gram.

5.The applic atio n pro gram rec eives the results and repeats steps 1 thro ugh 4 as needed to c o mplete the task.

With a sto red pro c edure, this pro c ess is muc h different. Befo re the pro gram is run, the fo llo wing steps o c c ur:

1.The sto red pro c edure is transmitted to the database server.

2.The sto red pro c edure is parsed and c o mpiled.

3.The c o mpiled c o de is saved fo r later exec utio n.

Then when the applic atio n pro gram is ready to perfo rm the same task:

1.The applic atio n pro gram transmits a request to c all the sto red pro c edure o ver the netwo rk.

2.The database server retrieves the c o mpiled c o py o f the sto red pro c edure and exec utes it.

3.The results are returned to the applic atio n pro gram.

(3)

Increasing convenience

Sto red pro c edures c an be c alled by different applic atio n pro grams o r c alled by any pro gram that is c apable o f direc tly exec uting SQL statements. This means that yo u c an develo p standard sto red pro c edures that perfo rm a task that c an be shared amo ng all o f yo ur applic atio ns. Bec ause the lo gic fo r the sto red pro c edure is iso lated to a single plac e (i.e., the database server), yo u c an c hange the sto red pro c edure witho ut nec essarily c hanging the applic atio n that c alls it. Thus, yo u c an c hange yo ur underlying database struc ture, while leaving yo ur applic atio ns unto uc hed.

Providing security

Sinc e a sto red pro c edure is just ano ther datab ase o b jec t, it c an b e sec ured using the same tec hniq ues used to sec ure o ther datab ase o b jec ts. Thus, yo u c an c reate a sto red pro c edure that allo ws yo ur users to perfo rm a partic ular task that they might no t o therwise b e ab le to perfo rm. Fo r instanc e, yo u might c reate a sto red pro c edure to insert a ro w in a tab le that yo ur users do n’t no rmally have ac c ess to .

Introducing Transact-SQL

Transac t-SQL ( also kno wn as T-SQL) is the name o f Mic ro so ft’s implementatio n o f SQL o n SQL Server. In additio n to the SQL statements I’ve used thro ugho ut this b o o k, there are a numb er o f extensio ns that allo w yo u to b uild c o mplex sto red pro c edures. Like any pro gramming language, Transac t-SQL c o nsists o f a numb er o f syntax elements, suc h as identifiers, data types, variab les, func tio ns, expres-sio ns, and statements.

(4)

Slash asterisk, asterisk slash c o mments c an be used anywhere a spac e c an be used; thus, they c an be embedded in yo ur c o de. A slash asterisk (/*) marks the start o f the c o mment, while an asterisk slash marks the end o f a c o mment (*/) . The c o m-ment may span multiple lines, as sho wn belo w:

/*

** Procedure: GetCustomerByName ** Written by: Wayne S. Freeze ** Date written: 28 April 2000

** Description: This procedure returns a customer’s ** information for a particular customer id.

*/

CREATE PROCEDURE GetCustomerByName

(@CustId Int /* customer id must be non-negative */ ) AS

Select * From Customers

Where CustomerId = @CustId

Hiding code: Som etim es w hen you are debugging a stored procedure, it is useful to hide blocks of code from the server so they are not executed. One easy w ay to do this is to insert a line containing a slash asterisk before the code you w ant to hide and an asterisk slash after the code.

Identifiers

An ide ntifie ris simply the name o f a database o bjec t, suc h as a database, table, o r c o lumn. It c an also be a Transac t-SQL keywo rd o r the name o f a variable o r label within a sto red pro c edure.

There are two different types o f identifiers: de limite d ide ntifie rsand re gular ide nti-fie rs.Delimited identifiers c an be any c o mbinatio n o f c harac ters up to 128 to tal. Yo u may use letters, numbers, spac es, and any spec ial symbo l exc ept fo r do uble quo tes (“) o r square brac kets ([]) . This is bec ause yo u must enc lo se the identifier in do u-ble quo tes o r inside a pair o f square brac kets. So me examples o f delimited identi-fiers are:

“My Table”

[This identifier includes a comma, an asterisk * and a period.]

Regular identifiers must begin with a letter, an undersc o re (_) , an at sign (@) , o r a number sign (#) and c an also c o ntain up to a maximum o f 128 c harac ters. The first c harac ter signifies ho w the identifier is used. System func tio ns begin with two at signs (@@) . Variables begin with an at sign, while a number sign identifies a tempo -rary table. So me examples o f regular identifiers are:

MyTable

@LocalVariable

(5)

Variables

Variable sin T-SQL are basic ally the same as they are in Visual Basic . They ho ld info rmatio n lo c al to the sto red pro c edure o r represent parameters passed to the sto red pro c edures. Variables begin with an at sign (@) and must be dec lared befo re they c an be used. Befo re yo u c an use a variable, yo u must dec lare it as a lo c al vari-able using the De clare statement o r as a parameter using the Cre ate Proce dure

statement.

Eac h variable must be assigned a valid data type that is c o mpatible with ho w yo u plan to use it. Yo u c an c ho o se fro m the same data types that yo u wo uld use in a

Cre ate Tablestatement, exc ept fo r Te xt, Nte xt, and Image. In the fo llo wing exam-ple, I dec lare two variables, @Counterand @Name, whic h are assigned Intand

Varchardata types respec tively.

Declare @Counter Int Declare @Name Varchar(64)

Functions

Functio nsin T-SQL are identic al to tho se in Visual Basic . They take a series o f zero o r mo re parameters and return a value to the c alling pro gram. Table 25-1 c o ntains so me o f the func tio ns that are available fo r yo u to use in yo ur sto red pro c edure.

Table 25-1

Selected functions in T-SQL

Function Description

@@CPU_Busy Returns the num ber of m illiseconds of CPU tim e SQL Server has consum ed since it w as started.

@@Cursor_Rows Returns the num ber of qualifying row s for the m ost recently opened cursor.

@@DBTS Returns the next tim estam p for the database.

@@Error Returns the error code for the m ore recently executed SQL statem ent.

@@Fetch_Status Returns the status of the last Fetchoperation.

@@IO_Busy Returns the num ber of m illiseconds SQL Server has spent perform ing I/ O.

@@Nestlevel Returns the nesting level of the current stored procedure. First level has a value of zero.

(6)

Table 25-1

(continued)

Function Description

@@Servername Returns the nam e of the database server.

@@Trancount Returns the current nesting level of a set of nested transactions.

@@Version Returns the date, version, and processor type for the database server.

App_Name Returns the nam e of the current application.

ASCII Returns the ASCII code of the left-m ost character of the specified character string.

Cast Converts a value in one data type to another data type.

Ceiling Returns the sm allest integer value greater or equal to the specified value.

Char Returns the character corresponding to the specified num eric ASCII code value.

Col_Length Returns the length of the specified colum n.

Columnproperty Returns the requested inform ation about the specified colum n.

Convert Returns the specified value using the specified data type using the specified style.

Current_User Returns the nam e of the current user.

Cursor_Status Returns the status of the specified cursor.

Datalength Returns the num ber of bytes in the specified expression.

Floor Returns the largest integer value less than or equal to the specified value.

Getdate Returns the current date and tim e as a Datetimevalue.

Host_Name Returns the nam e of the current com puter. (Not the database server.)

Len Returns the num ber of characters in a string, excluding trailing blanks.

Lower Converts all uppercase characters to low ercase.

Ltrim Rem oves leading blanks from a string.

IsDate Returns Trueif the specified expression contains a valid date.

IsNumeric Returns Trueif the specified expression is a valid num ber.

Is_M ember Returns Trueif the current user is a m em ber of the specified role.

(7)

Function Description

Object_Name Returns the nam e of the specified object identification num ber.

Patindex Returns the location of a pattern in the specified string.

Rand Returns a random value betw een 0 and 1.

Round Rounds the specified value to the specified length or precision.

Rtrim Rem oves trailing blanks from a string.

Substring Returns the specified part of a string.

Suser_Sid Returns the security identification num ber for the specified login nam e.

Suser_Sname Returns the login nam e for the current user or the login nam e for the specified security identification num ber.

Typeproperty Returns the requested inform ation about a data type.

Upper Converts all low ercase characters to uppercase.

Confusing, isn’t it: To prevent confusion w ith system functions, you should never declare a variable w ith double at signs.

Expressions

Expre ssio nsare used to c o mpute a single value based o n a series o f lo c al variables, parameters, c o lumns retrieved fro m a table, and func tio ns. Yo u c an assign an expressio n to a variable by using the Se tstatement, as sho wn here.

Set @Counter = 0

Set @MyString = Upper(Rtrim(CustomerName))

Yo u may also assign a value to a lo c al variab le using the Se le ctstatement. The o nly restric tio n is that the Se le ctstatement must return o nly o ne ro w. Otherwise, the variab le will b e assigned the last value retrieved b y the Se le ctstatement. In fro nt o f eac h c o lumn, yo u must spec ify the lo c al variab le, fo llo wed b y an eq ual sign ( =) , and then the c o lumn name. A simple example is sho wn b elo w:

Select @Name = Name, @EMail = EMailAddress From Customers

Where CustomerId = @CustId

Flow control

T-SQL inc ludes flo w c o ntro ls statements, suc h as If and While ,to help yo u build yo ur sto red pro c edures. Yo u c an even c all o ther sto red pro c edures using the

Exe cutestatement.

(8)

If statement

Yo u c o nstruc t an Ifstatement using the fo llo wing syntax:

If <boolean_expression>

{ <sql_statement> | Begin <sql_statement_list> End } [Else

{ <sql_statement> | Begin <sql_statement_list> End }]

If <boolean_expression> is True, then the statement that immediately fo llo ws the expressio n will be exec uted. Otherwise, the statement that immediately fo llo ws the

Elsec lause will be exec uted. Yo u c an substitute a Be gin Endpair that surro unds a list o f SQL statements fo r the single statements if yo u want to exec ute o ne o r mo re statements.

Beginnings and endings: Use Beginand Endclauses even if you only have a sin-gle statem ent. This m akes it easy to include additional statem ents in the future.

While statement

Whilestatements are c o nstruc ted with the fo llo wing syntax:

While <boolean_expression>

{ <sql_statement> | Begin <sql_statement_list> End }

The statement o r blo c k o f statements delimited by the Be gin Endpair are repeated until the <boolean_expression>is False. Inside a Be gin End pair, yo u c an end a

Whilelo o p early by using the Bre akstatement. The Continuestatement igno res the rest o f the statements in the Whilelo o p and restarts the lo o p.

Execute statement

The basic syntax fo r the Exe cutestatement’s syntax is sho wn belo w:

[Execute] [<return>=] <procedure_name> [[<parm>=]{<value>|<var>}]...

The Exe cutestatement is used to c all ano ther sto red pro c edure. While the ac tual syntax is mo re c o mplex, c hanc es are yo u’re no t go ing to use muc h mo re than this. No te that the Exe cutepart o f the statement may be o mitted. If the sto red pro c edure returns a value, yo u must inc lude a lo c al variable fo r <return>. Otherwise, this c lause sho uld be o mitted.

The name o f a sto red pro c edure fo llo ws no rmal database rules fo r the mo st part. Ho wever, if the name o f a sto red pro c edure begins with sp_, then the database server will searc h the master database fo r the sto red pro c edure rather than the lo c al database. If the name o f the sto red pro c edure isn’t qualified and it isn’t fo und under the c urrent user name, the database server will searc h fo r the sto red pro c e-dure using the dboas the o wner o f the sto red pro c edure.

(9)

Fo r example, if yo u are ac c essing the database with the user name MyUserand spec ify the sto red pro c edure name MyProc, SQL Server will lo o k fo r the sto red pro -c edure named MyUser.MyProcin the c urrent database. If it isn’t fo und then it will lo o k fo r the a sto red pro c edure named dbo.MyProcalso in the c urrent database. If it still isn’t fo und, then it will return an erro r message saying the sto red pro c edure c o uldn’t be fo und. This appro ac h allo ws yo u to test a sto red pro c edure with the same name and mo ve it to under dboo nly when yo u’re satisfied it wo rks pro perly. No w if yo u c all the sto red pro c edure, sp_MyProc, SQL Server will lo o k fo r the sto red pro c edure dbo.sp_MyProcin the master database. If it isn’t fo und there, then it will lo o k fo r the sto red pro c edure MyUser.sp_MyProcin the c urrent database. If it still isn’t fo und, then it will lo o k fo r the sto red pro c edure dbo.sp_MyProcin the c urrent database. The reaso n it wo rks this way is that yo u c an’t o verride ho w a system sto red pro c edure wo rks. Overriding a system sto red pro c edure c o uld c o mpro mise sec urity.

There are two ways to spec ify parameters: yo u c an simply list them in the o rder they were defined in the sto red pro c edure, o r yo u may assign a value explic itly to eac h parameter name. No te that if yo u list the parameters explic itly, yo u need no t wo rry abo ut the o rder yo u use.

The fo llo wing c alls are identic al:

Execute MyProc @MyVar, 24 MyProc @MyVar, 24

Execute MyProc @Parm1 = @MyVar, @Parm2 = 24 MyProc @Parm2 = 24, @Parm1 = @MyVar

Exectly: You can also abbreviate Executeas Exec.

Cursors

Curso rsare used to allo w yo u to sc ro ll thro ugh a set o f ro ws identified by a Se le ct

statement. The c urso r maintains the c urrent rec o rd po inter and allo ws yo u to use o ther statements, suc h as Fe tchto retrieve info rmatio n fro m the c urrent rec o rd into lo c al variables, and Updateto c hange the values in the c urrent rec o rd.

Declare Cursor

This De clare Cursorstatement defines a po inter and c an be used to ac c ess o ne ro w o f data returned by a Se le ctstatement:

Declare <cursor> Cursor [Local|Global]

[Static | Keyset | Dynamic | Fast_Forward] [Read_Only | Scroll_Locks | Optimistic] For <select_statement>

(10)

The <cursor>is a no rmal SQL Server identifier that will b e used b y o ther state-ments to ac c ess the c urso r. The Localkeywo rd implies that the c urso r c an’t b e ac c essed o utside this ro utine, while the Globalkeywo rd implies that the c urso r c an b e ac c essed b y o ther sto red pro c edures as lo ng as the c urrent c o nnec tio n to the datab ase is still ac tive.

The Statickeywo rd means that the database server will make a tempo rary c o py o f the data in tempdb to prevent mo dific atio ns to the data while yo u are pro c essing it. The Keysetkeywo rd instruc ts the database server to keep a list o f po inters to the ro ws, whic h means that yo ur sto red pro c edure will see the c urrent values to the ro ws, but no t ro ws that were added after the c urso r was o pened. The Dynamic key-wo rd implies that any and all c hanges made to the selec ted ro ws will be visible to the sto red pro c edure. Ho wever, this also implies that the o rder o f ro ws may c hange as new ro ws are added and existing ro ws deleted. The Fast_Forwardkeywo rd implies that the ro ws c an’t be c hanged and that the c urso r may o nly be mo ved in a fo rward direc tio n (i.e., yo u c an o nly use the Fetch Nextstatement).

The Re ad_Onlykeywo rd ensures that the ro ws c an’t be c hanged. Scroll_Locks

implies that ro ws are lo c ked when they are fetc hed, so that updates and deletes will always suc c eed. Spec ifying Optimisticmeans that the ro w isn’t lo c ked until yo u are ready to c o mmit the c hanges. This also implies that there is the po ssibility that the c hanges may fail bec ause the ro ws were c hanged by ano ther pro gram.

Where did I see that before: The keyw ords described here refer to the cursors and locking m echanism s that are available in ADO.

Open

In o rder to use the c urso r, yo u have to use the Ope nstatement. Its syntax is listed belo w:

Open <c urso r>

The Ope nstatement essentially exec utes the Se le ct statement and c reates the data struc tures nec essary to ac c ess the ro ws yo u selec ted.

Fetch

The syntax fo r the Fe tchstatement fo llo ws:

Fetch [Next|Prior|First|Last|Absolute <location>|Relative <offset>]

From <cursor> Into <variable_list>

The Fe tchstatement is used to retrieve info rmatio n fro m a ro w. If Ne xt, Prior, First,

Last, Absolute ,o r Re lativeare spec ified, then the mo vement is perfo rmed befo re the info rmatio n is returned. If the first c all to Fe tchafter o pening the c urso r inc ludes

(11)

the Ne xtkeywo rd, the c urrent rec o rd po inter is mo ved to the first ro w and Fe tch

returns the values fro m the first ro w. Fo r Fast_Forwardc urso rs, Ne xtis the o nly allo wable mo vement o ptio n.

The Absolutekeywo rd allo ws yo u to mo ve the c urrent rec o rd po inter to the spec i-fied ro w, where the first ro w is Absolute1 and the sec o nd ro w is Absolute2. The last ro w wo uld be kno wn as Absolute–1, while the next to the last ro w wo uld be fo und by using Absolute–2. The Absolutekeywo rd is no t legal when using a

Dynamicc urso r.

The Re lativekeywo rd allo ws yo u to mo ve the c urrent po inter relative to the c ur-rent rec o rd po inter. If the c urur-rent rec o rd po inter is po inting to ro w 7, Re lative–2 will repo sitio n the c urrent rec o rd po inter to ro w 5, while Re lative3 will mo ve the c urrent rec o rd po inter to ro w 10.

The Intoc lause requires that yo u supply a series o f lo c al variables to rec eive the c o lumns fro m the Se le ctstatement. The lo c al variables must be c o mpatible with the data types returned in the Se le ctstatement and must appear in the same o rder as tho se listed in the Se le ctstatement. A runtime erro r will o c c ur if there are to o few o r to o many variables listed in the Intoc lause.

Update

The syntax fo r using the Updatestatement with c urso rs is sho wn belo w:

Update <table> Set [<column> = <value>] ... Where Current Of <cursor>

If yo u De clarea c urso r that maps to a table, yo u c an use the Updatestatement to update the ro w at the c urrent rec o rd po inted to by the spec ified c urso r by using the Whe re Curre nt Of c lause. In plac e o f <value>yo u may use any expressio n o f the appro priate data type, inc luding func tio ns and lo c al variables.

Delete

Sho wn belo w is the syntax fo r using the De le testatement with a c urso r:

Delete From <table> Where Current of <cursor>

Substituting the table name o f the table used in the De clare Cursorstatement fo r

<table>and the name o f the c urso r fo r <cursor>will allo w yo u to delete the ro w that is po inted to by the c urso r’s c urrent rec o rd po inter.

Where did my row go?:If you delete a row in a cursor’s row set and later try to read the row w ith a Fetch statem ent w hen you declared the cursor as Staticor

Keyset, the @@Fetch_Statusfunction w ill return –2, m eaning that the row has been deleted.

(12)

Close

The syntax fo r the Closestatement is listed belo w:

Close <cursor>

The Closestatement releases the results o btained when the spec ified c urso r was o pened. Any lo c ks held also released.

Deallocate

The syntax fo r the De allocatestatement is listed belo w:

Deallocate <cursor>

Just bec ause yo u have c lo sed the c urso r do esn’t mean that the c urso r is no lo nger available. Yo u must De allocatethe c urso r to free all o f the reso urc es o wned by the c urso r.

An example of how to use a cursor

Rather than try to b uild a small example fo r eac h o f the ab o ve statements, I wro te a simple ro utine that demo nstrates ho w to retrieve so me info rmatio n fro m yo ur datab ase ( see Listing 25-1) . This ro utine retrieves names fro m the Custo mers tab le and prints them ( see Figure 25-1) .

Listing 25-1:

Using cursors in a simple stored procedure

Declare @CustName VarChar(64) Declare @RecCount Int

Declare CustCursor Cursor Local Fast_Forward Read_Only

For Select Name From Customers Where State = ‘MD’ Open CustCursor

Set @RecCount = 0

Fetch Next From CustCursor Into @CustName While @@Fetch_Status = 0

Begin

Print @CustName

Set @RecCount = @RecCount + 1

(13)

Print RTrim(Convert(VarChar(20), @RecCount)) + ‘ records found.’

Close CustCursor Deallocate CustCursor

Figure 25-1: Running the sam ple routine

The ro utine begins by dec laring variables to ho ld the c usto mer’s name and the num-ber o f rec o rds pro c essed. Then it dec lares a c urso r c alled CustCursorthat will be used to ac c ess the info rmatio n in the Custo mers table. To keep the amo unt o f data to a minimum, I selec ted o nly tho se c usto mers that live in Maryland. I also dec lare the c urso r as lo c al to this ro utine and c ho o se to make it Fast_Forwardand

Re ad_Onlysinc e I’m just go ing to read the data in a single pass.

(14)

At the end o f the ro utine, I print the to tal number o f rec o rds fo und, using the Convert

func tio n to c o nvert the value in @RecCountto a string value. Then I Closethe c urso r and Deallocateit. This frees all o f the reso urc es asso c iated with the c urso r.

Processing transactions

No w that yo u kno w ho w to build simple T-SQL pro grams that c an ac c ess individual ro ws in yo ur database, I want to c o ver the fac ilities fo r transac tio n pro c essing. As yo u might expec t, these fac ilities parallel tho se fo und in ADO. Basic ally, yo u mark the beginning o f a transac tio n and then yo u c an either save the c hanges yo u made to the database o r abo rt the c hanges witho ut c hanging the database.

Begin Transaction

Be gin Transactionmarks the start o f a transac tio n. This statement has the fo llo w-ing syntax:

Begin Transaction [<transaction_name>]

Yo u do n’t have to spec ify a value fo r <transaction_name>, but if yo u do , it must be a unique name fo llo wing the standard rules fo r identifiers, tho ugh o nly the first 32 c harac ters will be used. The names are o nly used fo r the o utermo st level o f a set o f nested transac tio ns, tho ugh yo u may want to assign a name to any nested trans-ac tio ns as well to c larify whic h Be gin Transactionis matc hed with whic h Commit Transactiono r Rollback Transaction.

When using nested transac tio ns, eac h new Be gin Transactioninc rements the value in @@Trancount. This is impo rtant, sinc e o nly the o uter mo st transac tio n c an c o m-mit the c hanges to the database. Of c o urse, the inner transac tio ns must c o mplete suc c essfully and have their results c o mmitted as well, but c hanges aren’t ac tually po sted to the database until the o utermo st transac tio n is c o mmitted.

Commit Transaction

The Commit Transactionstatement saves the c hanges made by a transac tio n to the database. This statement has the fo llo wing syntax:

Commit Transaction [<transaction_name>]

If the <transaction_name>parameter is spec ified, it must matc h the c o rrespo nd-ing value in the Be gin Transactionstatement.

Rollback Transaction

The Rollback Transactionstatement disc ards all o f the c hanges made by a transac -tio n to the database. This statement has the fo llo wing syntax:

(15)

If the <transaction_name>parameter is spec ified, it must matc h the c o rrespo nd-ing value in the Be gin Transactionstatement.

Other useful statements

There are a few o ther T-SQL statements that yo u may find useful when building a sto red pro c edure that do n’t fit into any o f the c atego ries I’ve disc ussed so far.

Use

The Usestatement spec ifies the database that will bec o me the default database and has the fo llo wing syntax:

Use <database>

Yo u c an use this statement at the beginning o f a sto red pro c edure to ensure that the sto red pro c edure is running in the appro priate database. Yo u c an also use the

Usestatement to switc h databases in the middle o f a sto red pro c edure.

User must exist in order to use Use: In order to sw itch databases, the person’s login m ust m ap to a valid user, otherw ise an error w ill occur.

Print

The Printstatement is used to return a userdefined message to the c alling pro -gram. The syntax o f print is:

Print <string_expression>

where <string_expression>c an be a string o f text enc lo sed by quo tes suc h as

‘text’, a lo c al variable o r func tio n who se data type is either Charo r Varchar, o r an expressio n that evaluates to a Charo r Varcharvalue, suc h as Conve rto r the string c o nc atenatio n o perato r (+) .

So me c o mmo n uses o f thePrintstatement are:

Print ‘Hello Raymond’

Print Convert(Varchar(20), @@CPU_Busy)

Print ‘CPU Busy is ‘ + Convert(Varchar(20), @@CPU_Busy)

Raiserror

Ano ther way to return info rmatio n to the c alling pro gram is to use the Raise rror

statement.

Raiserror (<message>, <severity>, <state> [, <argument_list>])

(16)

Calling Raise rrorsimply sets a system flag to rec o rd that an erro r o c c urred. Yo ur sto red pro c edure will c o ntinue to run no rmally. The <message>parameter is either a numeric value that refers to a user-defined message in the sysmessages table o r a string c o ntaining a c usto m erro r message. Yo u c an c ho o se to allo w values to be substituted into <message>by spec ifying a list o f values in <argument_list>and inc luding C style printffo rmatting c o mmands in <message>.

Yo u must also spec ify a severity c o de in <severity>. This value c an range fro m 0 to 18 fo r no rmal users and 19 to 25 fo r users with the sysadmin fixed server ro le. Severity levels greater than 19 are c o nsidered fatal, and they will immediately termi-nate the c o nnec tio n to the database. Otherwise the exac t meaning o f <severity>

is up to yo u.

But it’s almost fatal: You should use a severity of 19 for non-fatal errors in stored procedures running under the sysadm in fixed server role.

The <state>value pro vides additio nal info rmatio n abo ut the partic ular erro r. It c an range fro m 1 to 127. This value has no meaning o utside the c o ntext o f the erro r message.

Add your own errors: You can add errors to the sysm essages table by calling the

sp_addmessage stored procedure. You m ay delete a m essage by calling the

sp_dropmessagestored procedure.

Which way is right?: In Visual Basic, RaiseErroris spelled w ith tw o E’s, w hile in T-SQL Raiserroris spelled w ith one E.

Go

Tec hnic ally, Goisn’t a T-SQL statement, but a c o mmand that is used by Query Analyzer and so me o ther query to o ls to exec ute the gro up o f T-SQL statements that prec ede the Goc o mmand. Gomust o c c upy a line by itself in o rder to be pro perly rec o gnized.

Fo r instanc e, the fo llo wing statements are exec uted as a single batc h:

Declare @MDCount Int Select @MDCount = Count(*) From Customers

Where State = ‘MD’ Declare @SDCount Int Select @SDCount = Count(*) From Customers

Where State = ‘SD’

(17)

Print ‘MD Count = ‘ + Convert(Varchar(10),@MDCount) Print ‘SD Count = ‘ + Convert(varchar(10),@SDCount)

while these statements are exec uted as two independent gro ups:

Declare @MDCount Int Select @MDCount = Count(*) From Customers

Where State = ‘MD’

Print “MD Count = “ + Convert(Varchar(10),@MDCount) Go

Declare @SDCount Int Select @SDCount = Count(*) From Customers

Where State = ‘SD’

Print ‘SD Count = ‘ + Convert(varchar(10),@SDCount)

Finally, these statements will generate an erro r in the first Printstatement bec ause the variable @MDCountwill no lo nger be in sc o pe.

Declare @MDCount Int Select @MDCount = Count(*) From Customers

Where State = ‘MD’ Go

Declare @SDCount Int Select @SDCount = Count(*) From Customers

Where State = ‘SD’

Print ‘MD Count = ‘ + Convert(Varchar(10),@MDCount) Print ‘SD Count = ‘ + convert(varchar(10),@SDCount)

Creating and Testing Stored Procedures

While c reating and testing a sto red pro c edure isn’t very diffic ult, it is very c umber-so me. Yo u have to develo p the c o de using a to o l like Query Analyzer, unless yo u’re o ne o f tho se perfec t pro grammers who se c o de always runs c o rrec tly the first time. Then yo u have to save the c o de into the database as part o f a Cre ate Proce dureo r

(18)

Creating stored procedures in SQL Server

Sto red pro c edures c reated by using the Create Procedure statement are kept in sys-tem tables in yo ur database. The Create Procedure statement supplies the name o f the sto red pro c edure and the list o f parameters asso c iated with it. Fo llo wing the As

c lause is the list o f SQL statements that c o mprise the sto red pro c edure.

Create Procedure <procedure>

[<parameter> <data_type> [= <default>]] ... As <sql_statement> [<sql_statement>] ...

Yo u c an use Enterprise Manager to c reate a sto red pro c edure by fo llo wing these steps:

1.Expand the ic o n tree to sho w the Sto red Pro c edures ic o n beneath the database where yo u want to c reate the sto red pro c edure. Right c lic k o n the Sto red Pro c edures ic o n and selec t New Sto red Pro c edure to sho w the Sto red Pro c edure Pro perties windo w ( see Figure 25-2) .

Figure 25-2: Creating a new stored procedure

2.Replac e [PROCEDURE NAME]with the name yo u wish to c all yo ur sto red pro c edures and inc lude any parameters that b elo ng to the pro c edure imme-diately after the name. Then add the b o dy o f yo ur sto red pro c edure ( see Figure 25-3) .

3.Press the Chec k Syntax b utto n to verify that the syntax is c o rrec t. If there’s an erro r, a message b o x will b e displayed c o ntaining a sho rt desc riptio n o f the erro r. Otherwise, a message b o x saying Syntax c hec k suc c essful! will b e displayed.

(19)

Figure 25-3: Typing your stored procedure into the Properties w indow

Changes anyone: You can change your stored procedure anytim e by right clicking on the stored procedure nam e in the Details w indow and choosing Properties from the pop-up m enu. The sam e Properties w indow you used to create your stored procedure w ill be displayed, though the Create Procedure statem ent w ill be changed to Alter Procedure.

Another way to do it:You can also execute the sam e Create Procedure state-m ent in Query Analyzer to create a stored procedure.

Rename me twice:If you choose to renam e your stored procedure by using the pop-up m enu Renam e com m and in Enterprise Manager, you m ust rem em ber to open the Properties w indow for the stored procedure and correct its nam e in the

Alter Procedurecom m and.

Testing stored procedures in Query Analyzer

Query Analyzer is a general-purpo se to o l that allo ws yo u to run SQL statements interac tively. This also inc ludes sto red pro c edures. There are two ways to test yo ur pro c edure. First yo u c an use the T-SQL debugger to yo ur sto red pro c edure. Sec o nd, yo u c an test the blo c k o f c o de standalo ne Query Analyzer. This invo lves running the individual statements direc tly in Query Analyzer and verifying that they do what yo u want them to . Then yo u c an c reate the sto red pro c edure and c all it using Query Analyzer.

Fo r example, the sto red pro c edure I just wro te c an easily be run in Query Analyzer by typing its name fo llo wed by a Custo merId value ( see Figure 25-4) . This is a go o d way to make sure that yo u are getting the results yo u want befo re yo u build a Visual Basic pro gram to use it.

(20)

Figure 25-4: Running the stored procedure in Query Analyzer

But VB’s better: Rem em ber that Visual Basic includes a com prehensive stored procedure debugger, called the T-SQL Debugger. You can set breakpoints, exam ine variables and single step through the code. Refer to Chapter 13, “ Using Com m ands and Stored Procedures,” for details about how to use this pow erful tool.

Tip

Thoughts on Stored Procedures in SQL Server

Stored procedures are a pow erful tool in SQL Server that can m ake a big difference in how your application runs. They also are a w ay to isolate your application from the underlying database system , since you could create a series of stored procedures for each database m anagem ent system you use.

(21)

Summary

In this c hapter yo u learned:

✦ho w sto red pro c edures c an impro ve perfo rmanc e, inc rease c o nvenienc e and pro vide sec urity.

✦abo ut the features o f Transac t-SQL.

✦ab o ut the statements availab le in Transac t-SQL that help yo u write sto red pro c edures.

✦ho w to use c urso rs in Transac t-SQL.

✦ho w to pro c ess transac tio ns in Transac t-SQL.

✦ho t to c reate and test sto red pro c edures using Enterprise Manager and Query Analyzer.

(22)

Gambar

Table 25-1Selected functions in T-SQL
Table 25-1 (continued)
Figure 25-1: Running the sample routine
Figure 25-2: Creating a new stored procedure
+3

Referensi

Dokumen terkait

You can download and install the soft file of this incredible book Time Mends (Timber Wolves, Book 2) By Tammy Blackwell currently and in the link offered.. Yeah, different with

Indonesia merupakan negara dengan orang muslim terbesar didunia, akan tetapi setiap ormas muslim sendiri tentunya berbeda dalam memutuskan suatu masalah baru yang muncul

54 Tahun 2010 tentang Pengadaan Barang/Jasa Pemerintah serta menindaklanjuti proses seleksi untuk Paket Pekerjaan Pengadaan Meubelair (985 Unit) , bersama ini kami

n salinannya sebagaimana tertuang dalam lam proses pembuktian kualifikasi

Uang merupakan uang milik masyarakat atau uang beredar di masyarakat (di luar Bank Sentral seperti Bank Indonesia dan perbankan atau semua bank), yang terdiri dari :.. Uang Kertas

Puji syukur kami panjatkan kepada Tuhan Yang Maha Esa atas limpahan rahmat dan hidayah-Nya sehingga Prosiding Seminar Nasional MIPA Universitas Negeri Yogyakarta

As everybody recognizes, book Carr: Five Years Of Rape And Murder By Edna Buchanan is very popular as the window to open up the globe. It implies that reading publication Carr:

Teori investasi menjelaskan bahwa ketidakpastian IHSG pada suatu pasar bursa disebabkan oleh adanya pengaruh faktor lingkungan bisnis yang terdiri dari faktor lingkungan