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

25
C H A P T E R

Creating Stored
Procedures with
SQL Server









In This Cha pter
Intro ducing sto red
pro cedures

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 implementatio 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 diffic ult task. Yet sto red pro c edures c an make a big differenc 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: perfo rmanc e, c o nvenienc e, and sec urity. A sto red pro c edure usually 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

Using Transact-SQ L
to build sto red
pro cedures
Creating sto red
pro cedures with
SQ L Server
Debug g ing sto red
pro cedures in Q uery
Analyzer










558

Part VI ✦ SQL Server

a c o mplic ated pro gramming o bjec t that c an be used as easily as a no rmal SQL statement. 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 exec 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.
No te that there is o nly o ne interac tio n between the applic atio n pro gram and the
database server. This reduc es netwo rk traffic , whic h c an make a big differenc e o n
heavily-lo aded o r lo w-speed netwo rks. Also , the sto red pro c edure is c o mpiled befo re
the applic atio n c alls it. This saves a lo t o f wo rk fo r the database server, sinc e parsing and c o mpiling SQL statements c an be very CPU-intensive.

Chapter 25 ✦ Creating Stored Procedures with SQL Server

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 database o bjec t, it c an be sec ured using
the same tec hniques used to sec ure o ther database o bjec 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 be able 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 table 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, expressio ns, and statements.

Comments
It’s always a go o d idea to inc lude c o mments in yo ur c o de. There are two types o f
c o mment indic ato rs yo u may use: do uble hyphen ( --) and slash asterisk, asterisk
slash ( /* */).Do uble hyphen c o mments are usually used at the end o f a line o f
c o de, tho ugh they c an be plac ed o n a line by themselves. Everything fro m the do uble hyphens to the end o f the line is treated as a c o mment and is igno red by the
parser. Fo r example:

--- 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)
AS
Select *
From Customers
Where CustomerId = @CustId

559

560

Part VI ✦ SQL Server

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 mment 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
Tip

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 r is 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 rs and re gular ide ntifie 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 uble quo tes o r inside a pair o f square brac kets. So me examples o f delimited identifiers 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

Chapter 25 ✦ Creating Stored Procedures with SQL Server

Variables

Variable s in 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 variable using the Declare statement o r as a parameter using the Create Procedure
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
Create Table statement, exc ept fo r Text, Ntext, and Image . In the fo llo wing example, I dec lare two variables, @Counter and @Name, whic h are assigned Int and
Varchar data types respec tively.

Declare @Counter Int
Declare @Name Varchar(64)

Functions
Functio ns in 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 Fetch operation.

@@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.
Continued

561

562

Part VI ✦ SQL Server

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 Datetime value.

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 True if the specified expression contains a valid date.

IsNumeric

Returns True if the specified expression is a valid num ber.

Is_M ember

Returns True if the current user is a m em ber of the specified
role.

Object_Id

Converts the specified database object into a num eric object
identification num ber.

Chapter 25 ✦ Creating Stored Procedures with SQL Server

Tip

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 ns are 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 Set statement, as sho wn here.

Set @Counter = 0
Set @MyString = Upper(Rtrim(CustomerName))
Yo u may also assign a value to a lo c al variable using the Se le ct statement. The o nly
restric tio n is that the Se le ct statement must return o nly o ne ro w. Otherwise, the
variable will be assigned the last value retrieved by the Se le ct statement. In fro nt
o f eac h c o lumn, yo u must spec ify the lo c al variable, fo llo wed by an equal sign ( =) ,
and then the c o lumn name. A simple example is sho wn belo 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
Execute statement.

563

564

Part VI ✦ SQL Server

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

If
{ | Begin End }
[Else
{ | Begin End }]
If 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
Else c lause will be exec uted. Yo u c an substitute a Begin End pair 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.
Tip

Beginnings and endings: Use Begin and End clauses even if you only have a single statem ent. This m akes it easy to include additional statem ents in the future.

While statement
While statements are c o nstruc ted with the fo llo wing syntax:
While
{ | Begin End }
The statement o r blo c k o f statements delimited by the Begin End pair are repeated
until the is False . Inside a Begin End pair, yo u c an end a
While lo o p early by using the Break statement. The Continue statement igno res
the rest o f the statements in the While lo o p and restarts the lo o p.

Execute statement
The basic syntax fo r the Execute statement’s syntax is sho wn belo w:

[Execute] [=]
[[=]{|}]...
The Execute statement 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 Execute part 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 . 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 edure using the dbo as the o wner o f the sto red pro c edure.

Chapter 25 ✦ Creating Stored Procedures with SQL Server

Fo r example, if yo u are ac c essing the database with the user name MyUser and
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.MyProc in 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.MyProc also 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 dbo o 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_MyProc in 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_MyProc in 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_MyProc in 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
Tip

Exectly: You can also abbreviate Execute as Exec.

Cursors
Curso rs are used to allo w yo u to sc ro ll thro ugh a set o f ro ws identified by a Select
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 Fetch to retrieve info rmatio n fro m the c urrent rec o rd
into lo c al variables, and Update to c hange the values in the c urrent rec o rd.

Declare Cursor
This Declare Cursor statement defines a po inter and c an be used to ac c ess o ne ro w
o f data returned by a Select statement:

Declare Cursor
[Local|Global]
[Static | Keyset | Dynamic | Fast_Forward]
[Read_Only | Scroll_Locks | Optimistic]
For

565

566

Part VI ✦ SQL Server

The is a no rmal SQL Server identifier that will be used by o ther statements to ac c ess the c urso r. The Local keywo rd implies that the c urso r c an’t be
ac c essed o utside this ro utine, while the Global keywo rd implies that the c urso r
c an be ac c essed by o ther sto red pro c edures as lo ng as the c urrent c o nnec tio n to
the database is still ac tive.
The Static keywo 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 Keyset keywo 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 keywo 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_Forward keywo 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 Next statement).
The Read_Only keywo 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 Optimistic means 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.
Note

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 Open statement. Its syntax is listed
belo w:
Open
The Open statement essentially exec utes the Select 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 Fetch statement fo llo ws:

Fetch [Next|Prior|First|Last|Absolute |Relative
]
From Into
The Fetch statement is used to retrieve info rmatio n fro m a ro w. If Next, Prior, First,
Last, Absolute, o r Relative are spec ified, then the mo vement is perfo rmed befo re
the info rmatio n is returned. If the first c all to Fetch after o pening the c urso r inc ludes

Chapter 25 ✦ Creating Stored Procedures with SQL Server

the Next keywo rd, the c urrent rec o rd po inter is mo ved to the first ro w and Fetch
returns the values fro m the first ro w. Fo r Fast_Forward c urso rs, Next is the o nly
allo wable mo vement o ptio n.
The Absolute keywo rd allo ws yo u to mo ve the c urrent rec o rd po inter to the spec ified ro w, where the first ro w is Absolute 1 and the sec o nd ro w is Absolute 2. 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 Absolute keywo rd is no t legal when using a
Dynamic c urso r.
The Relative keywo rd allo ws yo u to mo ve the c urrent po inter relative to the c urrent rec o rd po inter. If the c urrent rec o rd po inter is po inting to ro w 7, Relative –2
will repo sitio n the c urrent rec o rd po inter to ro w 5, while Relative 3 will mo ve the
c urrent rec o rd po inter to ro w 10.
The Into c lause requires that yo u supply a series o f lo c al variables to rec eive the
c o lumns fro m the Select statement. The lo c al variables must be c o mpatible with
the data types returned in the Select statement and must appear in the same o rder
as tho se listed in the Select statement. A runtime erro r will o c c ur if there are to o
few o r to o many variables listed in the Into c lause.

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

Update Set [ = ] ...
Where Current Of
If yo u Declare a c urso r that maps to a table, yo u c an use the Update statement 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 Where Current Of c lause. In plac e o f 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 Delete statement with a c urso r:

Delete From
Where Current of
Substituting the table name o f the table used in the Declare Cursor statement fo r
and the name o f the c urso r fo r 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.
Note

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 Static or
Keyset , the @@Fetch_Status function w ill return –2, m eaning that the row has
been deleted.

567

568

Part VI ✦ SQL Server

Close
The syntax fo r the Close statement is listed belo w:

Close
The Close statement 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 Deallocate statement is listed belo w:

Deallocate
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 Deallocate the 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 build a small example fo r eac h o f the abo 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
database ( see Listing 25-1) . This ro utine retrieves names fro m the Custo mers table
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
Fetch Next From CustCursor Into @CustName
End

Chapter 25 ✦ Creating Stored Procedures with SQL Server

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 number o f rec o rds pro c essed. Then it dec lares a c urso r c alled CustCursor that 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_Forward and
Read_Only sinc e I’m just go ing to read the data in a single pass.
Next, I use the Open statement to o pen the c urso r and retrieve the info rmatio n
fro m the database. After setting @RecCount to zero , I fetc h the info rmatio n fro m the
first ro w into @CustName and start a While lo o p that will pro c ess the rest o f the ro w
in the c urso r’s ro wset. Fo r eac h ro w, I print the value saved in @CustName and use
the Fetch Next statement to retrieve the next value. This pro c ess c o ntinues as lo ng
as the Fetch statement is suc c essful ( @@Fetch_Status =0).

569

570

Part VI ✦ SQL Server

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 @RecCount to a string value. Then I Close the c urso r
and Deallocate it. 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
Begin Transaction marks the start o f a transac tio n. This statement has the fo llo wing syntax:

Begin Transaction []
Yo u do n’t have to spec ify a value fo r , 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 transac tio ns as well to c larify whic h Begin Transaction is matc hed with whic h Commit
Transaction o r Rollback Transaction .
When using nested transac tio ns, eac h new Begin Transaction inc 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 mmit 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 Transaction statement saves the c hanges made by a transac tio n to the
database. This statement has the fo llo wing syntax:

Commit Transaction []
If the parameter is spec ified, it must matc h the c o rrespo nding value in the Begin Transaction statement.

Rollback Transaction
The Rollback Transaction statement 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:

Rollback Transaction []

Chapter 25 ✦ Creating Stored Procedures with SQL Server

If the parameter is spec ified, it must matc h the c o rrespo nding value in the Begin Transaction statement.

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 Use statement spec ifies the database that will bec o me the default database and
has the fo llo wing syntax:

Use
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
Use statement to switc h databases in the middle o f a sto red pro c edure.
Note

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 Print statement is used to return a user-defined message to the c alling pro gram. The syntax o f print is:

Print
where 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 Char o r Varchar, o r
an expressio n that evaluates to a Char o r Varchar value, suc h as Convert o r the
string c o nc atenatio n o perato r ( +).
So me c o mmo n uses o f the Print statement 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 Raiserror
statement.

Raiserror (, , [, ])

571

572

Part VI ✦ SQL Server

Calling Raiserror simply 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 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 by spec ifying a list o f values in and
inc luding C style printf fo rmatting c o mmands in .
Yo u must also spec ify a severity c o de in . 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 terminate the c o nnec tio n to the database. Otherwise the exac t meaning o f
is up to yo u.
Note

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 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.
Tip

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_dropmessage stored procedure.

Caution

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

Go
Tec hnic ally, Go isn’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 Go c o mmand. Go must 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’

Chapter 25 ✦ Creating Stored Procedures with SQL Server

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 Print statement bec ause
the variable @MDCount will 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 umberso 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 Create Procedure o r
Alter Procedure statement using either Query Analyzer o r Enterprise. Next, yo u
have to build the Visual Basic pro gram to ac c ess the sto red pro c edure and verify
that it wo rks the way yo u expec t it. Of c o urse it wo n’t, so yo u may have to revise
the c o de using Query Analyzer and try it o ver again. Fo rtunately, Visual Basic
inc ludes a so phistic ated T-SQL debugger to help yo u tro ublesho o t why yo ur sto red
pro c edure didn’t wo rk as designed.

573

574

Part VI ✦ SQL Server

Creating stored procedures in SQL Server
Sto red pro c edures c reated by using the Create Procedure statement are kept in system 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
[ [= ]] ...
As [] ...
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 immediately 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 butto n to verify that the syntax is c o rrec t. If there’s
an erro r, a message bo x will be displayed c o ntaining a sho rt desc riptio n o f
the erro r. Otherwise, a message bo x saying Syntax c hec k suc c essful! will be
displayed.

4. Press OK to save yo ur sto red pro c edure.

Chapter 25 ✦ Creating Stored Procedures with SQL Server

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

Tip

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.

Note

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

Caution

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 Procedure com 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.

575

576

Part VI ✦ SQL Server

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

Tip

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.

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.
How ever, in SQL Server, stored procedures to encapsulate sim ple SQL statem ents aren’t as
critical as they are in other database m anagem ent system s. SQL Server 7 w ill rem em ber the
SQL statem ents you have used recently and reuse the com piled code if the query is the
sam e. This m akes param eterized queries nearly as efficient as stored procedures and som ew hat easier to use.

Chapter 25 ✦ Creating Stored Procedures with SQL Server

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.
✦ abo ut the statements available 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.







577