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

13

C H A P T E R

Using
Commands
and Stored
Procedures

I

n this c hapter, I will c o ver ho w to c reate and use ADO
Command o bjec ts. The Command o bjec t allo ws yo u to spec ify a c o mmand that will retrieve data fro m yo ur database.
Typic ally this o bjec t is used with sto red pro c edures and
SQL queries that inc lude a series o f parameters.

Introducing the ADO
Command Object
After yo u have an o pen c o nnec tio n, the first thing yo u’re go ing
to want to do is to exec ute so me c o mmands. Co mmands are
defined in the Command o bjec t and c an be SQL statements o r

c alls to sto red pro c edures. So me c o mmands, partic ularly tho se
that use sto red pro c edures, may have parameters that supply
additio nal info rmatio n to the c o mmand o r return info rmatio n
after the c o mmand was exec uted. Parameter info rmatio n is
sto red in the Parameters c o llec tio n, with eac h parameter having its o wn Parameter o bjec t. Also , depending o n the partic ular c o mmand, it may o r may no t return a Recordset o bjec t
c o ntaining ro ws o f info rmatio n fro m yo ur database.
CrossReference

Discussing Command objects w ithout talking about Recordset
objects can be difficult, since the prim ary reason for using
Command objects is to create Recordsets. See Chapter 14 for
m ore inform ation about Recordset objects.

✦✦✦✦
In This Cha pter
Presenting the ADO
Command O bject
Intro ducing the ADO
Parameter O bject
W o rking with the

ADO Parameters
Co llectio n
Creating and
executing co mmands
Using sto red
pro cedures









236

Part III ✦ Hardcore ADO

The Command Object

The Command o bjec t c o ntains info rmatio n abo ut an SQL statement o r sto red pro c edure yo u wish to exec ute against a database. Yo u may o ptio nally inc lude a list o f
parameters that will be passed to the sto red pro c edure. If the c o mmand returns a
set o f ro ws, the Command o bjec t will return a Recordset o bjec t c o ntaining the
results.

Command object properties
Table 13-1 lists the pro perties asso c iated with the Command o bjec t.

Table 13-1
Properties of the Command Object
Property

Description

ActiveConnection

A Variant array containing an object reference to the
Connection object used to access the database. May also
contain a valid connection string that w ill dynam ically create a
connection to your database w hen you use the Execute

m ethod.

CommandText

A String value containing an SQL statem ent, a stored procedure
nam e, or other provider com m and to be executed.

CommandTimeout

A Long value containing the m axim um num ber of seconds for
the com m and to execute before an error is returned. Default is 30
seconds.

CommandType

An enum erated type (see Table 13-2) describing the type of
com m and to be executed.

Name


A String containing the nam e of the object.

Parameters

An object reference to a Parameters collection containing the
param eters that w ill be passed to a stored procedure or a
param eterized query.

Prepared

A Boolean, w hen TRUE, m eans that the com m and should be
prepared before execution.

Properties

An object reference to a Properties collection containing
additional inform ation about the Command object.

State


A Long describing the current state of the Command object.
Multiple values from Table 13-3 can be com bined to describe the
current state.

Chapter 13 ✦ Using Commands and Stored Procedures

Table 13-2
Values for CommandType
Constant

Value

Description

adCmdUnspecified

-1

CommandType should be autom atically
determ ined.


adCmdText

CommandText contains either an SQL

1

statem ent or stored procedure call.

adCmdTable

CommandText contains the nam e of a table in

2

the database.

adCmdStoredProcedure

CommandText contains the nam e of a stored


4

procedure.

adCmdUnknown

8

The type of com m and isn’t know n.

adExecuteNoRecords

128

Indicates that the com m and w ill not return any
row s or w ill autom atically discard any row s that
are generated. Must be used w ith adCmdText
or adCmdStoredProcedure.


adCmdFile

256

CommandText is the nam e of a persistently
stored Recordset.

adCmdTableDirect

512

CommandText contains the nam e of a database
table.

Table 13-3
Values for State
Constant

Value


Description

adStateClosed

0

The Command object is closed.

adStateOpen

1

The Command object is open.

adStateConnecting

2

The Command object is connecting to the
database.


adStateExecuting

4

The Command object is executing.

adStateFetching

8

Row s are being retrieved.

237

238

Part III ✦ Hardcore ADO

Command bject methods
The Command o bjec t c o ntains o nly three metho ds: Cancel, CreateParameter, and
Execute.

Sub Cancel( )
The Cancel metho d is used to terminate an async hro no us task started by the
Execute metho d.

Function CreateParameter ([Name As String], [Type As DataTypeEnum =
adEmpty], [Direction As ParameterDirectionEnum = adParamInput],
[Size As Long], [Value]) As Parameter
The CreateParameter metho d c reates a new Parameter o bjec t, whic h may be
added to the Parameters c o llec tio n using the Parameters.Append metho d.

Name spec ifies the name o f the parameter.
Type spec ifies the data type o f the parameter.
Direction spec ifies whether the parameter is input o nly, o utput o nly, o r bo th
input and o utput.
Size spec ifies the length o f the parameter. This parameter is o nly impo rtant when
yo u have a variable length data type, suc h as a string o r an array.
Value spec ifies the value o f the parameter.

Function Execute ([RecordsAffected], [Parameters],
[Options As Long = -1]) As Recordset
The Execute metho d runs the SQL statement o r sto red pro c edure spec ified in the
Command o bjec t. A Recordset o bjec t will be returned as the result o f the func tio n,
whic h will c o ntain any ro ws returned by the c o mmand.

RecordsAffected o ptio nally returns a Long value with the number o f rec o rds
affec ted by the c o mmand.
Parameters o ptio nally passes a Variant array c o ntaining a list o f parameters to
be used by the c o mmand. No te that o utput parameters will no t return c o rrec t values thro ugh this parameter. Instead, yo u sho uld use the Parameters c o llec tio n to
get the c o rrec t values fo r o utput parameters.

Chapter 13 ✦ Using Commands and Stored Procedures

Options o ptio nally passes a c o mbinatio n o f the values spec ified in Table 13-4. No te
that so me o f these values are the same as tho se available fo r the CommandType
pro perty.

Table 13-4
Values for Options
Constant

Value

Description

adOptionUnspecified

-1

No options are specified.

adCmdText

1

CommandText contains either an SQL
statem ent or stored procedure call.

adCmdTable

2

CommandText contains the nam e of a table
in the database.

adCmdStoredProcedure

4

CommandText contains the nam e of a stored
procedure.

adCmdUnknown

8

The type of com m and isn’t know n.

adAsyncExecute

16

The com m and should be executed
asynchronously.

adAsyncFetch

32

After the num ber of row s specified in the

CacheSize property of the Recordset
object are returned, the rem aining row s w ill
be returned asynchronously.

adAsyncFetchNonBlocking

64

The m ain thread isn’t blocked w hile retrieving
row s. If the current row hasn’t been retrieved,
the current row w ill be m oved to the end of
the file.

adExecuteNoRecords

128

Indicates that the com m and w ill not return
any row s or w ill autom atically discard any
row s that are generated. Must be used w ith
either the adCmdText or
adCmdStoredProcedure values.

adCmdFile

256

CommandText is the nam e of a persistently
stored Recordset.

adCmdTableDirect

512

CommandText contains the nam e of a
database table.

239

240

Part III ✦ Hardcore ADO

The Parameter Object
The Parameter o bjec t c o ntains info rmatio n abo ut a parameter used in a sto red
pro c edure o r parameterized query defined in a Command o bjec t.

Parameter object properties
Table 13-6 lists the pro perties asso c iated with the Parameter o bjec t.

Table 13-6
Properties of the Parameter Object
Property

Description

Attributes

An enum erated type describing the characteristics of the param eter
(see Table 13-7).

Direction

An enum erated type that describes w hether the param eter is an inputonly, input/ outpu, or output-only param eter (see Table 13-8).

Name

A String value containing the nam e of the param eter.

NumericScale

A Byte value containing the num ber of digits to the right of the
decim al point for a num eric field.

Precision

A Byte value containing the total num ber of digits in a num eric field.

Properties

An object reference to a Properties collection containing providerspecific inform ation about a param eter.

Type

An enum erated type (see Table 13-9) containing the OLE DB data type
of the field.

Value

A Variant array containing the current value of the param eter.

Table 13-7
Values for Attributes
Constant

Value

Description

adFldUnspecified

-1

The provider doesn’t supply field attributes.

adFldMayDefer

2

The field value is not retrieved w ith the
w hole record, but only w hen you explicitly
access the field.

Chapter 13 ✦ Using Commands and Stored Procedures

Constant

Value

Description

adFldUpdateable

4

The field’s value m ay be changed.

adFldUnknownUpdateable

8

The provider can’t determ ine if you can
change the field’s value.

adFldFixed

16

The field contains fixed-length data.

adFldIsNullable

32

The field w ill accept Null values.

adFldMayBeNull

64

The field m ay contain a Null value.

adFldLong

128

The field contains a long binary value and
you should use the AppendChunk and
GetChunk m ethods to access its data.

adFldRowID

256

The field contains an identity value that
can’t be changed.

adFldRowVersion

512

The field contains a tim e stam p value that is
used to track updates.

adFldCacheDeferred

4096

This field is cached by the provider and
subsequent reads and w rites are done from
cache.

adFldIsChapter

8192

The field contains a chapter value, w hich
specifies a specific child Recordset related
to this parent field.

adFldNegativeScale

16384

The field contains a num eric colum n that
supports negative scale values.

adFldKeyColumn

32768

The field is (or is at least part of) the
prim ary key for the table.

adFldIsRowURL

65536

The field contains the URL that nam es the
resource from the data store represented by
the record.

adFldIsDefaultStream

131072

The field contains the default stream for the
resource represented by the record.

adFldIsCollection

262144

The field contains a collection of another
resource, such as a folder, rather than a
sim ple resource, such as a file.

241

242

Part III ✦ Hardcore ADO

Table 13-8
Values for Direction
Constant

Value

Description

adParamUnknown

0

The direction of the param eter is unknow n.

adParamInput

1

The param eter is an input-only param eter.

adParamOutput

2

The param eter is an output-only param eter.

adParamInputOutput

3

The param eter is both an input and an
output param eter.

adParamReturnValue

4

The param eter contains a return value.

Table 13-9
Values for Type
Constant

Value

Description

adEmpty

0

This field has no value ( DBTYPE_EMPTY).

adSmallInt

2

This field has an Integer value
( DBTYPE_I2).

adInteger

3

This field has a Long value ( DBTYPE_I4).

adSingle

4

This field has a Single value
( DBTYPE_R4).

adDouble

5

This field has a Double value
( DBTYPE_R8).

adCurrency

6

This field has a Currency value
( DBTYPE_CY).

adDate

7

This field has a Date value
( DBTYPE_DATE).

adBSTR

8

This field has a null-term inated Unicode
string ( DBTYPE_BSTR).

adIDispatch

9

This field has a pointer to an IDispatch
interface in a COM object
( DBTYPE_IDISPATCH).

adError

10

This field has a 32-bit error code
( DBTYPE_ERROR).

adBoolean

11

This field has a Boolean value
( DBTYPE_BOOL).

Chapter 13 ✦ Using Commands and Stored Procedures

Constant

Value

Description

adVariant

12

This field has a Variant value
( DBTYPE_VARIANT). Note that this type is
not supported by ADO and causes
unpredictable results.

adIUknown

13

This field has a pointer to an IUnknown
interface in a COM object ( DBTYPE_
IUNKNOWN).

adDecimal

14

This field has an exact num eric value w ith
a fixed precision and scale ( DBTYPE_
DECIMAL).

adTinyInt

16

This field has a one byte signed integer
( DBTYPE_I1).

adUnsignedTinyInt

17

This field has a one byte unsigned integer
( DBTYPE_UI1).

adUnsignedInt

18

This field has a tw o byte unsigned integer
( DBTYPE_UI2).

adUnsignedInt

19

This field has a four byte unsigned integer
( DBTYPE_UI4).

adBigInt

20

This field has an 8-byte signed integer
( DBTYPE_I8).

adUnsignedBigInt

21

This field has an 8-byte unsigned integer
( DBTYPE_UI8).

adFileTime

64

This field has a 64-bit date-tim e value
represented as the num ber of 100nanosecond intervals since 1 January 1601
( DBTYPE_FILETIME).

adGUID

72

This field has a globally unique identifier
value ( DBTYPE_GUID).

adBinary

128

This field has a Binary value ( DBTYPE_
BYTES).

adChar

129

This field has a String value ( DBTYPE_
STR).

adWChar

130

This field contains a null-term inated
Unicode character string ( DBTYPE_WSTR).

adNumeric

131

This field contains an exact num eric value
w ith a fixed precision and scale ( DBTYPE_
NUMERIC).
Continued

243

244

Part III ✦ Hardcore ADO

Table 13-9 (continued)
Constant

Value

Description

adUserDefined

132

This field contains a user-defined value
( DBTYPE_UDT).

adDBDate

133

This field has a date value using the
YYYYMMDD form at ( DBTYPE_DBDATE).

adDBTime

134

This field has a tim e value using the
HHMMSS form at ( DBTYPE_DBTIME).

adDBTimeStamp

135

This field has a date-tim e stam p in the
YYYYMMDDHHMMSS form at
( DBTYPE_DBTIMESTAMP).

adChapter

136

This field has a 4-byte chapter value that
identifies the row s in a child row set
( DBTYPE_HCHAPTER).

adPropVariant

138

This field has an Autom ation PROPVARIANT
( DBTYPE_PROP_VARIANT).

adVarNumeric

139

This field contains a num eric value.
(Available for Parameter objects only.)

adVarChar

200

This field has a String. (Available for
Parameter objects only.)

adLongVarChar

201

This field has a long character value.
(Available for Parameter objects only.)

adVarWChar

202

This field has a null-term inated Unicode
character string value. (Available for
Parameter objects only.)

adLongVarWChar

203

This field has a long null-term inated
character string value. (Available for
Parameter objects only.)

adVarBinary

204

This field has a binary value. (Available for
Parameter objects only.)

adLongVarBinary

205

This field has a long binary value. (Available
for Parameter objects only.)

Chapter 13 ✦ Using Commands and Stored Procedures

Parameter object methods
There is o nly o ne metho d available fo r the Parameter o bjec t: the AppendChunk
metho d.

Sub AppendChunk (Data As Variant)
The AppendChunk metho d is used to add data to a large text o r binary field. The
first time the AppendChunk metho d is used, the value in Data will o verwrite any
existing data in the field. Fo r subsequent c alls, simply append data to the end o f
the existing data. Data is a Variant array c o ntaining the data to be appended to
the end o f the field.

The Parameters Collection
The Parameters c o llec tio n c o ntains the set o f parameters asso c iated with a
Command o bjec t.

Parameters collection properties
Table 13-10 lists the pro perties asso c iated with the Parameters c o llec tio n.

Table 13-10
Properties of the Parameters Collection
Property

Description

Count

A Long value containing the num ber of Parameter objects in the
collection.

Item(index)

An object reference to a Parameter object containing inform ation
about a particular field in the Recordset. To locate a field, specify a
value in the range of 0 to Count –1 or the nam e of the
Parameter.

Parameters collection methods
The metho d available fo r the Parameters c o llec tio n allo ws yo u to manage the set
o f Parameter o bjec ts.

245

246

Part III ✦ Hardcore ADO

Sub Append (Object As Object)
The Append metho d adds a Parameter o bjec t to the c o llec tio n. The Type pro perty
o f the Parameter o bjec t must be defined befo re yo u c an add it to the c o llec tio n.
Object is a Parameter o bjec t c o ntaining the new parameter.
Tip

Use the CreateParameter m ethod of the Command object to create a new
Parameter object, then use the Append m ethod to add it to the collection.

Sub Delete (Index As Variant)
The Delete metho d remo ves an o bjec t spec ified by Index fro m the c o llec tio n.
Index is either a String value c o ntaining the name o f the parameter o r a Long
value c o ntaining the o rdinal po sitio n o f the Parameter o bjec t to be deleted.

Sub Refresh( )
The Refresh metho d c an b e used to retrieve info rmatio n ab o ut the parameters in
a sto red pro c edure fro m the data pro vider. To use Refresh in this fashio n, yo u
need a valid Command o b jec t with an ac tive c o nnec tio n to the data so urc e. Then
all yo u need to do is spec ify values fo r CommandText and CommandType and use
the Parameters.Refresh metho d. This will retrieve all o f the info rmatio n fo r the
sto red pro c edure fro m the data pro vider. No te that this wo rks o nly if yo ur data
pro vider suppo rts sto red pro c edures o r an SQL q uery with emb edded parameters
( also kno wn as a parame te riz e d que ry ) .

Running SQL Statements
A Command o bjec t c o ntains all o f the info rmatio n nec essary to send a c o mmand to
the database server fo r exec utio n. So metimes the c o mmand will need parameters,
while at o ther times it will no t. Depending o n the c o mmand yo u want to exec ute, it
may return no thing o r a Recordset o bjec t c o ntaining the set o f ro ws selec ted fro m
the database. No matter what the c o mmand is, the appro ac h yo u use to define it
and run it is basic ally the same.

Running a simple command
Every Command yo u exec ute needs at least two piec es o f info rmatio n befo re yo u c an
use it. Yo u must set the CommandText to the c o mmand yo u want to exec ute and yo u
must set the ActiveConnection pro perty to an o pen Connection o bjec t.
While no t as impo rtant, yo u sho uld set the CommandType pro perty to the value
appro priate fo r the c o mmand yo u want to exec ute. If this value is no t spec ified, o r
set to adCmdUnknown, the database server must determine if the c o mmand is an

Chapter 13 ✦ Using Commands and Stored Procedures

SQL statement, a sto red pro c edure, o r a table name befo re it c an exec ute it. While
this extra o verhead isn’t large by itself, it c an be signific ant when yo u multiply it by
the number o f requests the server must exec ute.
The Co mmand Demo pro gram (see Figure 13-1) is based o n the Co nnec tio n Demo
pro gram fro m Chapter 12. All o f the c o de and fo rm elements are c arried o ver intac t,
altho ugh I added a few new c o mmand butto ns and Click events to demo nstrate
ho w to use the Command o bjec t.

Figure 13-1: Running the Com m and
Dem o program

On the
CD-ROM

The Com m and Dem o program can be found on the CD-ROM in the
\ VB6DB\ Chapter13\ Com m andDem o directory.
.

Listing 13-1 sho ws ho w yo u c an use a Command o bjec t to c reate a database table. In
this example, I c reate a table c alled MyTable. Ho wever, this tec hnique c an be used
to exec ute any SQL statement exc ept fo r the Select statement. (The Select statement will return a Recordset o bjec t, whic h requires so me additio nal c o de.)

Listing 13-1: The Command5_Click event in Command Demo
Private Sub Command5_Click()
Dim c As ADODB.Command
On Error Resume Next
Continued

247

248

Part III ✦ Hardcore ADO

Listing 13-1 (continued)
Set c = New ADODB.Command
Set c.ActiveConnection = db
c.CommandText = “Create Table MyTable (MyColumn Char (10))”
c.CommandType = adCmdText
db.Errors.Clear
c.Execute
If db.Errors.Count > 0 Then
WriteError
End If
End Sub

Note

Once is okay, twice isn’t: Since this routine creates a table in your database, running it a second tim e w ill fail unless you rem ove the table m anually. You should
use a query tool to delete the table before you try it a second tim e or try it again to
see the error that w ill result from executing this com m and tw ice.

The ro utine begins by c reating a new instanc e o f the Command o bjec t and setting the
ActiveConnection pro perty to the same Connection o bjec t I c reated in Chapter 12.
Then I assign the SQL statement I want to exec ute to the CommandText pro perty. Sinc e
I’m exec uting an SQL statement, I’ll set the CommandType to adCmdText to prevent the
server fro m trying to determine if it is the name o f a table o r sto red pro c edure.
Onc e the c o mmand is defined, exec uting is easy. I Clear the Errors c o llec tio n to
make sure that any erro rs in the c o llec tio n are c aused by the Execute metho d.
Then I use the Execute metho d to run the c o mmand o n the database server. If
there are any erro rs in the Errors c o llec tio n, I’ll c all the WriteError ro utine to
display the info rmatio n.

Returning a Recordset
Wo rking with Recordsets is basic ally the same as wo rking with simple c o mmands
exc ept that the Execute metho d returns a referenc e to Recordset o bjec t. In Listing
13-2, I c reate a Connection o bjec t the same way as in Listing 13-1, but instead o f
the Create Table SQL statement, I use a Select statement.

Chapter 13 ✦ Using Commands and Stored Procedures

Listing 13-2: The Command4_Click event in Command Demo
Private Sub Command4_Click()
Dim c As ADODB.Command
Dim rs As ADODB.Recordset
On Error Resume Next
Set c = New ADODB.Command
Set c.ActiveConnection = db
c.CommandText = “Select Count(*) From Customers Where State =
‘MD’”
c.CommandType = adCmdText
db.Errors.Clear
Set rs = c.Execute
If db.Errors.Count > 0 Then
WriteError
Else
StatusBar1.SimpleText = “Response: “ & _
FormatNumber(rs.Fields(0).Value, 0)
End If
End Sub

Sinc e the c all to c.Execute will return an o bjec t referenc e, I need to use a Set
statement to assign the o bjec t referenc e to the Recordset o bjec t. No te that I didn’t
need to c reate an instanc e o f the Recordset o bjec t. The Execute metho d to o k c are
o f this fo r me.
Next, I c hec k fo r erro rs in the Errors c o llec tio n and c all the WriteError ro utine
if I find any. Otherwise, I o utput the value o f the first field in the first ro w o f the
Recordset in the status b ar. Yo u c an verify that the value is c o rrec t b y exec uting
the same q uery using yo ur datab ase q uery to o l.
Tip

Quick and dirty: Building and debugging a database application can be difficult. If
you’re truly paranoid, like m e, you don’t trust your application until you can verify
that it w orked properly using an independent tool. This is w here a tool like SQL
Server’s Query Analyzer com es in handy. You can use it to execute any type of
query you like. Thus, you can test your Select statem ent to ensure that the right
num ber of row s w as returned or to verify that an update to the database w as
m ade properly. You can also use it to test various SQL statem ents, and w hen
you’re satisfied that they’re correct, you can copy them to the CommandText property of a Command object.

249

250

Part III ✦ Hardcore ADO

Running with parameters
While kno wing the number o f c usto mers in Maryland is nic e, a better appro ac h
than c reating a Command o bjec t fo r eac h state wo uld be to c reate o ne that ac c epts
parameters. This is also an easy pro c ess, as yo u c an see in Listing 13-3. This ro utine
is based o n the o ne sho wn in Listing 13-2. The o nly differenc es are the o nes needed
fo r parameters.

Listing 13-3: The Command3_Click event in Command Demo
Private Sub Command3_Click()
Dim c As ADODB.Command
Dim p As ADODB.Parameter
Dim rs As ADODB.Recordset
On Error Resume Next
Set c = New ADODB.Command
Set c.ActiveConnection = db
c.CommandText = “Select Count(*) From Customers Where State =
?”
c.CommandType = adCmdText
Set p = c.CreateParameter(“State”, adChar, adParamInput, 2)
c.Parameters.Append p
c.Parameters(“State”).Value = Text3.Text
db.Errors.Clear
Set rs = c.Execute
If db.Errors.Count > 0 Then
WriteError
Else
StatusBar1.SimpleText = “Response: “ & _
FormatNumber(rs.Fields(0).Value, 0)
End If
End Sub

The first differenc e yo u might have no tic ed is that I assigned the Se le ct statement
to the CommandText pro perty. In plac e o f the MD, there is no w a questio n mark ( ?) .
Questio n marks are used to identify the plac e where a parameter will be substituted into the statement. In this c ase, the parameter is the two -c harac ter state
abbreviatio n.

Chapter 13 ✦ Using Commands and Stored Procedures

Next, I use the CreateParameter metho d to c reate a new Parameter o bjec t c alled
State. I’ll save the o bjec t referenc e in a tempo rary variable c alled p. It has a type o f
Char(2) and is an input-o nly parameter. The last argument o f the metho d is o mitted.
Had I wanted to assign a default value fo r the parameter, I wo uld have spec ified it as
the last parameter. After c reating the parameter, I use the Append metho d o f the
Parameters c o llec tio n to add the o bjec t to the c o llec tio n.
Note

Order in the parameters: The order in w hich you add the param eters to the collection is the sam e order that w ill be used to m atch the param eters to the question m arks in the CommandText. The first param eter is m apped to the first
question m ark, w hile the second param eter is m apped to the second question
m ark, and so on.

Onc e the parameter has been defined, yo u c an use the Parameters c o llec tio n to
identify the parameter by name and assign it a value. Then yo u c an use the
Execute metho d to generate the Recordset o bjec t and display the results.
An alternate way to exec ute a c o mmand with parameters is to supply the parameter values as part o f the Execute metho d, as sho wn in the fo llo wing line o f c o de:

Set rs = c.Execute(, Array(Text3.Text))
The sec o nd argument o f the Execute metho d allo ws yo u to spec ify a Variant
array c o ntaining a list o f parameters that will be used by the c o mmand. The easiest
way to c o nstruc t a Variant array is to use the Array func tio n, whic h takes a list o f
values and returns a Variant array c o ntaining the values. If yo u have already spec ified a parameter direc tly in the Parameters c o llec tio n, the value spec ified in the
Execute metho d will o verride that value.

Stored Procedures
Sto red pro c edures are useful to o ls that allo w yo u to exec ute a set o f SQL statements o n the database server by issuing a single c o mmand with a series o f parameters. Info rmatio n c an be returned via the Parameters c o llec tio n o r in a Recordset
o bjec t. Sto red pro c edures are highly dependent o n the database system o n whic h
they run. Ho wever, the benefits o f using sto red pro c edures o ften far o utweigh having SQL statements that are independent o f a partic ular database system.

Advantages of stored procedures
Many peo ple use sto red pro c edures in their database applic atio ns fo r three main
reaso ns: faster perfo rmanc e, applic atio n lo gic , and sec urity.

251

252

Part III ✦ Hardcore ADO

Faster performance
Using sto red pro c edures is typic ally faster than issuing the equivalent SQL statements fro m yo ur applic atio n, fo r several reaso ns. The first reaso n is that sto red
pro c edures are sto red o n the database server in a prepared fo rmat. This avo ids
the o verhead o f preparing a statement o n the fly. Also , if yo u repeatedly exec ute
the same statement, mo st database servers will prepare the statement eac h time
yo u exec ute it, impo sing a lo t o f extra o verhead o n the database server.
Note

Prepared for speed: Before any SQL statem ent can be executed, it m ust be prepared. Preparing a statem ent involves parsing the w ords in the statem ent, com piling them into a package, and then optim izing the package based on the data in
the database.

In additio n, sto red pro c edures o ften c o ntain multiple SQL statements, whic h means
that yo u do n’t have to wait fo r a respo nse ac ro ss the netwo rk befo re yo u send the
next c o mmand. The individual statements are exec uted in sequenc e until the sto red
pro c edure is c o mplete. This means that the intermediate rec o rdsets yo u wo uld
have transmitted to the c lient c o mputer, and the c o mmands yo u wo uld have issued
in respo nse, aren’t nec essary. Whic h in turn reduc es the amo unt o f time needed to
perfo rm the func tio n.

Application logic
Sto red pro c edures are written using a language that allo ws yo u to have lo c al variables, perfo rm c o mputatio ns, c all o ther sto red pro c edures, and pro c ess rec o rdsets — as well as exec ute SQL statements. In sho rt, yo u c an think o f a sto red
pro c edure muc h like yo u wo uld think o f a Visual Basic pro gram, but o ne who se
exec utio n is tightly c o upled with the database server.
Sinc e many develo pers find this c o nc ept appealing, they c o de their b usiness lo gic
as sto red pro c edures and make them availab le fo r applic atio n pro grammers to
use. This ensures that eac h pro gram c an take advantage o f the b usiness lo gic , and
as lo ng as the c alling seq uenc e isn’t c hanged, yo u wo n’t have to rec o mpile yo ur
Visual Basic pro gram eac h time a sto red pro c edure is c hanged.

Security
Using a sto red pro c edures c an be mo re sec ure than granting so meo ne direc t ac c ess
to a database. Sinc e sto red pro c edures are database o bjec ts, they are usually sec ured
using the same to o ls that yo u wo uld use fo r a table o r a view fo r user ac c ess, yet yo u
c an allo w the sto red pro c edure to run using so meo ne else’s database privileges. This
allo ws yo u to put c o de in a sto red pro c edure to perfo rm a spec ific func tio n that the
user might no t o therwise be able to perfo rm. The user will no t be able to see o r
c hange this c o de.

Chapter 13 ✦ Using Commands and Stored Procedures

Stored procedures and the Data View Window
In Chapter 9, I talked abo ut ho w to use the Data View Windo w (see Figure 13-2) to
ac c ess yo ur database while using the Data Enviro nment Designer. It’s po ssible to
use the Data View Windo w witho ut the Data Enviro nment Designer. Unlike the Data
Enviro nment Designer, the Data View Windo w isn’t integrated into yo ur pro gram. It
is a design-time o nly to o l that allo ws yo u to ac c ess yo ur database design, tables,
views, and sto red pro c edures tasks using a database vendo r independent to o l.

Figure 13-2: Adding the Data View
Window to your application

Note

Exclusively Enterprise Edition: The Data View Window features I’m going to cover
apply to the Enterprise Edition of Visual Basic. If you have the Professional Edition,
you w ill need to create and debug your stored procedures using tools provided by
your database vendor. This isn’t entirely bad, as I feel these tools are often better
than the ones supplied w ith Visual Basic.

Creating a Data Link
Befo re yo u c an use the Data View Windo w, yo u need to c reate a link to the database.
After o pening the Data View Windo w, right c lic k o n the Data Link ic o n and selec t Add
a Data Link fro m the po p-up menu. This will display the same Data Link Pro perties
dialo g bo x that yo u’ve seen many times by no w (see Figure 13-3). Simply selec t the
pro per OLE DB pro vider fo r yo ur database, enter the c o nnec tio n info rmatio n, and
press OK to return to the Data View Windo w.

253

254

Part III ✦ Hardcore ADO

Figure 13-3: View ing the Data Link
Properties w indow yet again

Creating a stored procedure
If yo u expand yo ur newly c reated Data Link ic o n, yo u’ll see eac h o f the fo ur types o f
o bjec ts available fo r yo u to manipulate: Database Diagrams, Tables, Views and Sto red
Pro c edures. Do uble c lic king o n the Sto red Pro c edures ic o n will display the list o f
sto red pro c edures in the database, and right c lic king o n the same ic o n and selec ting
New Sto red Pro c edure fro m the po -up menu will allo w yo u to c reate a new sto red pro c edure (see Figure 13-4).
The New Sto red Pro c edure windo w is a simple edito r with a series o f butto ns
ac ro ss the to p o f the sc reen. The same windo w will be used to edit an existing
sto red pro c edure. The o nly differenc e is that the name o f the existing sto red pro c edure will be displayed in the title bar. The ic o ns that appear in the to o lbar are
explained belo w:

✦ New Stored Procedure – pro mpts yo u to save yo ur c hanges and then displays a skeleto n sto red pro c edure fo r yo u to edit.

✦ Open Text File – asks if yo u want to o verwrite the existing text and then displays a File Open dialo g bo x to lo ad a text file into the edit windo w.

✦ Save to Database – saves yo ur sto red pro c edure to the database.

Chapter 13 ✦ Using Commands and Stored Procedures

New Stored Procedure
Save to
Database

Cut

Print

Paste

Find

Debug
Copy

Save as Text
Open Text File
Figure 13-4: Creating a stored procedure

✦ Save as Text – saves yo ur sto red pro c edure to a text file.
✦ Print – sends yo ur sto red pro c edure to the default Windo ws printer.
✦ Find – displays a Find dialo g bo x.
✦ Cut/ Copy/ Paste – perfo rms the standard editing func tio n using the c lipbo ard.
✦ Debug – starts the sto red pro c edure debugger.

Coding the stored procedure
Writing a sto red pro c edure is highly dependent o n the database server yo u use. The
example I’m go ing to use here is fo r the SQL Server 7. Ho wever, no matter who se
database system yo u’re using, all sto red pro c edures have so me things in c o mmo n.
First, they are all c reated using the Create Procedure SQL statement, and c an be

255

256

Part III ✦ Hardcore ADO

deleted with the Drop Procedure statement. The identifier that fo llo ws the Create
Procedure statement is the name o f the sto red pro c edure. Sec o nd, all sto red pro c edures ac c ept arguments that allo w yo u to pass parameters to them and return values fro m them. After the arguments are defined, yo u enter the statements that
c o mprise the sto red pro c edure.
The Sto red Pro c edure windo w allo ws yo u to build the Create Procedure statement
that will c reate yo ur sto red pro c edure. Listing 13-4 sho ws a sto red pro c edure that
perfo rms the same func tio n as the Select statement I’ve been using thro ugho ut this
c hapter in the sample pro gram. It takes a single parameter, @State that has a type
o f Char(2), whic h is the same type as the State c o lumn in the database. The @State
parameter is used in plac e o f the questio n mark in the parameterized Select statement in the previo us example.

Listing 13-4: The CountByState stored procedure
Create Procedure CountByState (@State Char(2)) As
Select Count(*)
From Customers
Where State = @State
Return

Saving the stored procedure
Pressing the Save to Database butto n will exec ute the Create Procedure statement o n
the database server and will c reate a sto red pro c edure using the name CountByState.
If yo u want to edit the sto red pro c edure, simply expand the Sto red Pro c edures ic o n o n
the Data View windo w and do uble c lic k o n CountByName. This will display the same
SQL statement, with o ne mino r differenc e. The wo rds Create Procedure will be
replac ed with Alter Procedure .

Debugging stored procedures
The T-SQL Debugger allo ws yo u to debug sto red pro c edures direc tly fro m Visual
Basic . This to o l o nly wo rks with SQL Server 6.5 and later databases. The debugger
c an be c alled direc tly fro m Visual Basic . Befo re yo u c an use the debugger, yo u must
install the appro priate c o de o n yo ur database server.

Installing the SQL Server debugging support
The setup pro gram is c o ntained in the \SQDBG_SS direc to ry o n disk 2 o f the Visual
Basic installatio n CD-ROMs. Yo u c an even run the setup pro gram while yo ur SQL
Server database is running.

Chapter 13 ✦ Using Commands and Stored Procedures

When yo u start the setup pro gram, yo u’ll see a dialo g bo x similar to the o ne sho wn
in Figure 13-5 reminding yo u that this utility is no t part o f SQL Server, but part o f
Visual Basic . If yo u agree with the lic ense info rmatio n, press the Co ntinue butto n.

Figure 13-5: Review ing license inform ation for the SQL
Server Debugging facility

The next few dialo g bo xes will ask yo u to verify yo ur name and o rganizatio n info rmatio n and to enter the CD Key fro m the bac k o f yo ur Visual Basic CD-ROM c ase.
Enter the info rmatio n as requested and press OK o r Co ntinue at eac h step o f the
wizard until yo u reac h the Installatio n dialo g bo x sho wn in Figure 13-6. Yo u c an
c hange the direc to ry where the so ftware will be installed by pressing the Change
Fo lder butto n. When yo u’re ready to begin, press the square Server butto n. The
setup pro gram will then install the debugging suppo rt feature.

Figure 13-6: Starting the installation program

257

258

Part III ✦ Hardcore ADO

Tip

I got this weird error: If you get a strange error w hile trying to start the T-SQL
Debugger and it instructs you to look in the client log on the database server, m ost
likely the SQL Server Debugging support has not been installed.

Setting T-SQL Debugging Options
Befo re yo u use the T-SQL Deb ugger, yo u sho uld review the o ptio ns. To display
the o ptio ns, c ho o se To o ls ➪ T-SQL Deb ugging Optio ns fro m the Visual Basic main
menu. This will b ring up the T-SQL Deb ugging Optio ns dialo g b o x, as sho wn in
Figure 13-7.

Figure 13-7: Setting debugging options

There are fo ur o ptio ns yo u c an set. Chec king the Auto matically ste p into Sto re d
Pro ce dure s thro ugh RDO and ADO co nne ctio ns will auto matic ally start the debugger
anytime yo u exec ute a sto red pro c edure while running yo ur Visual Basic pro gram.
If this bo x is no t c hec ked, the debugger will no t be used at runtime. Chec king Use
Safe Mo de ( transactio n ro llback) fo r Sto re d Pro ce dure calls means that any c hanges
made by the sto red pro c edure while in debug mo de are disc arded.
Note

Sometimes it works and sometimes it doesn’t: I’ve noticed that changing these
properties don’t alw ays take effect the next tim e you run your program in the IDE.
I suggest running your program and ending it before you attem pt to do anything.
Then run the program again, and the debugger should behave properly.

The Limit SQL Output to the fo llo wing numbe r o f line s pe r re sultse t determines the
upper limit in the number o f ro ws that will be retrieved while debugging the pro c edure. This value helps to ensure that yo ur sto red pro c edure do esn’t run o ut o f c o ntro l. The Lo gin Time o ut value fo r re trie ving sto re d pro ce dure te xt sets the maximum
amo unt o f time the debugger will wait to c o nnec t to the database server.

Starting the T-SQL Debugger
Yo u c an run the T-SQL Debugger direc tly fro m Visual Basic by c ho o sing Add-Ins ÿ TSQL Debugger fro m the main menu. This will display the Visual Basic T-SQL Batc h
Debugger dialo g bo x (see Figure 13-8). Yo u need to pro vide the info rmatio n in this
windo w to c o nnec t to the database to selec t and run yo ur sto red pro c edure.

Chapter 13 ✦ Using Commands and Stored Procedures

Figure 13-8: Setting options in the T-SQL Debugger w indow

To c o nnec t to an SQL Server database using OLE DB, simply enter the name o f yo ur
database server in the SQL Server dro p-do wn bo x, spec ify the name o f the database
yo u want to use in the Database dro p do wn bo x, and supply yo ur user name and
passwo rd in the UID and Passwo rd fields. Yo u c an also define an ODBC c o nnec tio n
by pressing the Define DSN butto n.
Onc e these values are set, the Sto red Pro c edure and Batc h Query tabs will be
enabled. To debug a sto red pro c edure, selec t the Sto red Pro c edure tab (see Figure
13-9) and c ho o se the sto red pro c edure yo u want to debug in the Pro c edure Name
dro p-do wn bo x. Then selec t eac h o f the parameters listed in the Parame te rs area
and assign them the values yo u want to use during the exec utio n.

Figure 13-9: Selecting the stored procedure and entering
its param eters

259

260

Part III ✦ Hardcore ADO

Tip

Run simple queries: You can use the Batch Query tab in the Visual Basic T-SQL
Debugger to run any block of SQL statem ents you m ay choose using the T-SQL
Debugger.

Running the Debugger
After yo u have finished entering values fo r all o f the parameters, press the Exec ute
butto n o n the Sto red Pro c edure tab o f the Visual Basic Batc h T-SQL Debugger to
start a debugging sessio n. The T-SQL Debugger windo w will be displayed (see
Figure 13-10).

Toggle Breakpoint
Remove all Breakpoints
Step Info
Go
Select Query

Status

Step Over
Run to Cursor

Global Variables

Local Variables
and Parameters
Figure 13-10: Running the T-SQL Debugger

Results

Stored Procedure

Chapter 13 ✦ Using Commands and Stored Procedures

✦ Select Query – allo ws yo u to c ho o se fro m multiple queries yo u may be debugging at the same time.

✦ Go – runs the query to c o mpletio n fro m the c urrent statement o r to the next
breakpo int.

✦ Toggle Breakpoint – enables o r disables a breakpo int at the spec ified line o f
c o de.

✦ Removes All Breakpoints – remo ves all o f the breakpo ints in the sto red
pro c edure.

✦ Step Into – runs the sto red pro c edure until the spec ified subexpressio n is
reac hed

✦ Step Over – runs the selec ted subexpressio n.
✦ Run To Cursor – runs the sto red pro c edure up to where the c urso r is po inting.
✦ Stored Procedure – c o ntains the text o f the sto red pro c edure. This area is
used to display the c urrently ac tive statement and any breakpo ints that have
been set.

✦ Local Variables and Parameters – this sec tio n c o ntains variables lo c al to the
sto red pro c edure and their c urrent values. Yo u c an edit a value by do uble
c lic king o n the value to selec t it and entering a new value.

✦ Global Variables – this sec tio n c o ntains the glo bal variables fo r the sto red
pro c edure and their c urrent values. These values may also be c hanged while
the sto red pro c edure is waiting fo r user input.

✦ Results – displays any ro ws returned by a Select statement and also desc ribes
the c urrent state o f exec utio n.

✦ Status – desc ribes the c urrent state o f the debugger. If the message Waiting fo r
use r input is displayed, the debugger is in break mo de and waiting fo r yo u to
resume exec utio n.

Calling a stored procedure
As yo u might expec t, defining a sto red pro c edure in a Command o bjec t isn’t muc h
different than defining an SQL statement ( see Listing 13-5) . In plac e o f the SQL
statement, yo u will need to spec ify the name o f the sto red pro c edure in the
CommandText pro perty. Yo u sho uld spec ify adCmdStoredProc as the value o f
CommandType.
One advantage o f using sto red pro c edures is the ability to auto matic ally retrieve the
parameter definitio ns rather than manually defining eac h Parameter o bjec t and
adding it to the Parameters c o llec tio n. Simply use the Refresh metho d o f the
Parameters c o llec tio n to retrieve the definitio ns fro m the database. Then yo u may
assign values to eac h parameter by name as yo u did when yo u explic itly defined the
parameters.

261

262

Part III ✦ Hardcore ADO

Listing 13-5: The CountByState stored procedure
Private Sub Command6_Click()
Dim c As ADODB.Command
Dim p As ADODB.Parameter
Dim rs As ADODB.Recordset
On Error Resume Next
Set c = New ADODB.Command
Set c.ActiveConnection = db
c.CommandText = “CountByState”
c.CommandType = adCmdStoredProc
c.Parameters.Refresh
c.Parameters(“@State”).Value = Text4.Text
db.Errors.Clear
Set rs = c.Execute
If db.Errors.Count > 0 Then
WriteError
Else
StatusBar1.SimpleText = “Response: “ & _
FormatNumber(rs.Fields(0).Value, 0)
End If
End Sub

Thoughts on Stored Procedures
Using stored procedures is very im portant w hen building applications for Oracle. They can
m ake a significant difference in how your application perform s. How ever, stored procedures are not as im portant for SQL Server 7 databases. SQL Server 7 prepares an SQL statem ent the first tim e it encounters it during your program ’s execution and retains it so that
the next tim e you use it, it w on’t have to prepare it again. This doesn’t m ean that you
shouldn’t use stored procedures in SQL Server 7, because they don’t m ake as big of a difference as they do w ith an Oracle database.

Command objects are necessary w hen you w ant to execute a stored procedure or any SQL
statem ent other than a Select statem ent. Also, Command objects are im portant w hen you
w ant to use param eter-based queries. The rest of the tim e, you can perform the sam e function directly using the Recordset object, a topic that w ill be covered in the next chapter.

Chapter 13 ✦ Using Commands and Stored Procedures

Summary
In this c hapter yo u learned the fo llo wing:

✦ Yo u c an define a Command o bjec t to ho ld a frequently exec uted SQL statement
o r sto red pro c edure.

✦ Yo u c an define Parameter o bjec ts whic h c o ntain info rmatio n that is passed
to a sto red pro c edure o r parameterized query fo r exec utio n.

✦ Yo u c an easily c reate and edit sto red pro c edures direc tly in Visual Basic .
✦ Yo u c an install the sto red pro c edure debugger ro utines into yo ur database
server so that yo u c an debug sto red pro c edures direc tly fro m Visual Basic .







263