ASP 101 - Active Server Pages 101 - Web01
The Place ASP Developers Go!

Please visit our partners


Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates














ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash



 Top ASP 101 Stories Top ASP 101 Stories
What is Adovbs.inc and Why Do I Need It?
An Overview of ASP.NET
Connections, Commands, And Procedures

QUICK TIP:
Don't touch that mouse!
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates


BackContentsNext

Stored Procedures

The use of stored procedures is the one area where the Command object comes into its own. A stored procedure (or stored query as it's sometimes called) is a predefined SQL query stored on the database.

So why should we create and use a stored procedure instead of just creating a SQL string on the fly, as in the example shown above? Well, there are several reasons:

  • A stored procedure is compiled by the database. This produces an execution plan, so the database knows exactly what it's going to do. This makes the execution of the procedure faster.
  • Stored procedures are often cached by the database, thus making them faster to run, as they don't have to be read from disk. Not all databases support this caching mechanism - Microsoft Access doesn't, but SQL Server does.
  • You can make your data a little bit more secure by specifying that your database tables can be modified only by stored procedures. This means that potentially dangerous SQL operations generated on the fly may not be performed.
  • You avoid cluttering your ASP code with lengthy SQL statements. This makes the ASP code easier to maintain.
  • You can keep all of the SQL code together, on the server.
  • You can use output parameters in a stored procedure, which allows you to return both a recordset and other values.

As a general rule, stored procedures will nearly always be quicker than their equivalent SQL statements.

To use a stored procedure you just put the name of the stored procedure as the command text, and set the type accordingly. For example, consider the previous example of updating book prices. If we created a stored procedure on SQL Server, it might look like this:

For a Microsoft Access database you can create a simple update query to do the same task:

To run this stored procedure from an ASP page, you'd simply use the following code:

This simply runs the stored procedure. No recordset is returned, because we are only updating data - remember, there's no point creating a recordset unless one is needed.

As it stands though, this procedure isn't very flexible since it only deals with one book type. What would be better would be a procedure that allows us to select the book type so we don't have to create a procedure for each book type. And while we're at it, we might as well remove the fixed 10% update, and allow this to be flexible too. So, how do we achieve this - simple, with parameters.

Parameters

Parameters to stored procedures are just like parameters (or arguments, depending on your preferred term) to procedures and functions. These allow values to be passed into a function, and then the function can use the value. Stored procedures in SQL Server (and other databases, including Access) both have this facility.

To allow the procedure to cope with multiple book types, and even allow the user to specify the price increase (or decrease), we need to add some parameters:

The stored procedure usp_UpdatePrices now takes two parameters:

  • One for the book type (@Type)
  • One for the percentage change in price (@Percent)

Just like a VBScript function, these parameters are variables. However, unlike VBScript and other scripting languages where all the variables are variants, SQL variables all have specific types (Char, Money, etc). They must also follow the naming convention for SQL variables, which means they must start with an @ symbol.

Notice that we've allowed the percentage to be supplied as a whole number (for example 10 for 10%), instead of it's fractional value. This just makes the procedure more intuitive to use.

The Parameters Collection

So now we have a stored procedure with parameters, how do we actually call this from ADO? You've already seen how to call stored procedures without parameters using the Command object, and that doesn't change. What changes is the use of the Parameters collection.

The Parameters collection contains a Parameter object for each parameter in the stored procedure. However, ADO doesn't automatically know what these parameters are, so you have to create them, using the CreateParameter method, which takes the following form:

The arguments are:

Once the parameter is created it can be appended to the Parameters collection. For example:

There's no need to explicitly create an object to hold the parameter - the default type of Variant works well enough here. If you don't want to create a variable, you can also take a shortcut:

This uses the fact that the CreateParameter method returns a Parameter object, and the Append method accepts a Parameter object. This method is marginally faster than using a variable, but does make your lines of code longer and therefore harder to read. You can use whichever method you prefer.

You don't have to set the value of the parameter at the time you create the parameter, since once the parameter is appended to the Parameters collection it remains in the collection. You can therefore set the value any time before the command is run. For example:

In the previous chapter we mentioned that there are several ways of accessing values in collections, and the Parameters collection is no different. The above example uses the name of the parameter to index into the collection, but you could equally use the index number:

This sets the value of the first (collections are zero-based) parameter in the collection. The index number method is marginally faster that the name method, but obviously the name method makes your code much clearer to read.

One point that is important to note is that the parameters in the Parameters collection must match the order of the parameters in the stored procedure.

Running Parameter Commands

Once the parameters have been added, the command can now be run and these parameter values will be passed into the stored procedure. So now, you can make a nice page that updates selected book types. For example, let's imagine a page called UpdatePrices.asp, that looks like this when run:

You could easily build this page dynamically, getting a list of book types from the database. The first thing we do is include the file Connection.asp - this contains the connection string (held in strConn) as well as the reference to the ADO constants, which we discussed in the previous chapter:

Next, we can build the form (we won't show the large text body here, but it's in the sample file). The form calls the ASP file called StoredProcedure.asp:

Now we can start the ASP script, to read in the book types from the titles table. We use a SQL string to return only the unique book types, and then put the returned values into HTML OPTION tags:

Once the book types have been displayed, we can construct the remainder of our form, including a text box allowing the user to enter the percentage change:

Let's now look at StoredProcedure.asp, the ASP page that the Run Query button calls. The first thing we do is declare the variables, and extract the book type and percentage from the calling form:

Now we can display some confirmation to the user of what's happening:

Now come the guts of the code, where we create the Command object and the parameters:

We use the shortcut method of creating and adding the parameters, using the values we've extracted from the previous pages form:

And now we can run the stored procedure:

And just for confirmation, we can tell the user how many records were updated:

So there we have two simple pages. The first builds a list of items to select and the second uses one of those items as a value in the update. This is the basis for many ASP pages that need to display and update data like this.

Passing Parameters as an Array

The Parameters collection is all very well, but it's a bit cumbersome (especially for those two fingered typists). Luckily there's a quick shortcut method, using the Parameters argument of the Execute method. For example, let's call our tame stored procedure, usp_UpdatePrices, but without using the Parameters collection.

We create the Command object and set it's properties in the same way as before:

But here's where the difference lies. Instead of creating parameters and adding them to the collection, we simply pass the parameters into the stored procedure via the Execute method:

This utilizes the Array function, which turns individual variables into an array, suitable for passing into this method call. As with every shortcut, there are of course some disadvantages to this method:

  • You can only use input parameters. Since you cannot specify type and direction of parameters they default to input parameters.
  • This method is slower if you intend to call the stored procedure several times, since ADO will ask the data store what the parameters are, and what data types they use.

The difference in speed between the collection method and the array method is so small that it's hardly noticeable, so if you only have input parameters you can use whichever method you prefer. I actually prefer the long-winded method of the Parameters collection, because it makes it more explicit what the properties of the parameters are.

Output Parameters

We've seen that you can get the number of records affected by a command, but what if you want more information, but still don't want to return a recordset. Perhaps you want two or three values returned from a stored procedure, but don't want to go to the overhead of creating a recordset. If this is the case you can define a parameter as an output parameter, where the value is supplied by the stored procedure.

For example, let's consider our price update routine. Suppose we want to find out the maximum book price after the update has taken place. Our stored procedure could be changed like this:

This just runs a simple SELECT after the update and places the value in the output parameter.

We can now change the code in StoredProcedure.asp accordingly to retrieve the value of @Max:

We simple add another parameter to the collection, but this time specifying it as an output parameter. Note that we don't give it a value. That's because the value will be supplied by the stored procedure - remember, it's an output parameter:

Once the procedure is executed we can retrieve the value from the collection:

If there is more than one output parameter, then they can be accessed in the same way. You can use the Parameter name or the index number to extract the value from the collection.

Return Values

Return values from functions are handled differently from the way return values from stored procedures are handled, and this often causes confusion. In user functions, we often return a Boolean value to indicate the success or failure of a function:

When calling a stored procedure though, we can't use the same method, because the stored procedures are run using the Execute method, and this returns a recordset:

If we can't get a return value, how do we determine if the stored procedure executed correctly? Well, if an error occurred this would be reported, and we could handle it with the error handling code shown in the previous chapter, but what about some sort of non-fatal logic error.

For example, consider adding a new employee to the employee table. You don't want to stop two people with the same name being added, but you might want this situation flagged. Here's where we could use a return value, to indicate whether an employee with the same name already exists. The stored procedure might look like this:

The first thing this procedure does is check to see if an employee with the same name exists, and sets a variable accordingly - it will be 1 if the employee exists, and 0 otherwise. The employee is then added to the table, and the Exists value is returned as the return value.

Notice that although we are returning a value we don't declare it as a parameter to the stored procedure.

The ASP code to call this procedure would look like:

The important thing to note is that the return value is created as the first parameter in the collection. Even though the return value doesn't appear as a parameter in the stored procedure, it is always the first Parameter in the Parameters collection.

So, just to stress this confusing point:

Return values from stored procedures must be declared as the first parameter in the Parameters collection, with a direction of adParamReturnValue.

Using Return Values

Now this is defined we could have an initial form like this:

Pressing the Add Employee button would then generate:

Adding the same details again (with a different employee ID) gives this:


BackContentsNext
©1999 Wrox Press Limited, US and UK.
Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers