Welcome!

ColdFusion Authors: Maureen O'Gara, Hovhannes Avoyan, Yakov Fain, Pat Romanski, Liz McMillan

Related Topics: ColdFusion

ColdFusion: Article

Using MS-SQL Stored Procedures with ColdFusion Part 3 of 3

Using MS-SQL Stored Procedures with ColdFusion Part 3 of 3

Now that we've gone over stored-procedure integration with ColdFusion and looked at some programming basics in Parts 1 and 2 of this article (CFDJ, Vol. 3, issues 10 and 12), let's look at some other useful and more complicated functions using MS-SQL2000.

First, however, I need to correct a statement I made in Part 1. I mentioned that stored procedures weren't good if you needed to cache a query on the Web server. However, I've since found out from Ben Forta's CF 4.0 Web Application Construction Kit that you can cache stored-procedure results and, further, run almost any T-SQL functions within <CFQUERY> as long as you're performing only one action. In other words, you can't run a SELECT and an UPDATE function within one <CFQUERY> tag.

Fortunately, when you need to cache a query it's usually a simple SELECT statement. Listing 1 shows a simple stored procedure that returns a list of states; Listing 2 shows the CF code to cache this stored procedure. This feature is limited to returning a single result set and can't return values like <CFPROCPARAM> can.

getDate() and dateAdd()
I frequently read about problems with passing dates into the database in the CF support forum. As long as you're simply inserting the date as a timestamp or need to do calculations on today's date, it's far easier to let the database do the processing through stored procedures than trying to format the date on the Web server into something the database likes. I'll be referring to this date field as a timestamp but it shouldn't be confused with the "timestamp" value type in T-SQL.

If you try to pass a timestamp into the database using the <CFPROCPARAM> tag with the type set to "datetime," you'll probably get a nice error message that says "Feature Not Implemented." Don't worry about the date on the Web server. T-SQL has a feature called "getDate()". It works the same way as "now()" in CF.

Each column in the database can have a default value. The value doesn't have to be a constant; it can be a function. If you use a date as a timestamp for entering records, simply set that "datetime" field to "getDate()" as the default. Then when you do your insert, ignore that column altogether and the database will put in the correct date in the correct format. Listing 3 shows how to do an insert statement using "getDate()" with <CFQUERY>, in case you don't trust the database to set the date automatically.

If you need to do addition or subtraction on dates, it works almost the same way as in CF. Even the syntax ("dateAdd(datepart, number, date)") is the same. The dateparts are also the same in T-SQL as in CF5 except for hour ("h"), which is "hh" in T-SQL. To subtract dates, use a negative number in the number field.

Triggers
What if you have a timestamp field that needs to be updated whenever a record is edited? T-SQL has a feature called triggers that lets the database take actions when rows are inserted, updated, or deleted. Triggers can be as complex as necessary, but I recommend keeping them simple because tracking errors can be very frustrating otherwise.

Let's look at a trigger for updating the timestamp when a row in a table is edited (see Listing 4).

CREATE TRIGGER tr_updateItemTS
ON Items
FOR UPDATE
AS
Each trigger must have a unique name. I prefix mine with "tr" for easy identification. The second line tells what type of action the trigger fires on. You can use "Update," "Insert," or "Delete" or any combination separated by commas.

DECLARE
@Item_Pk int

IF Update(ItemMin)
BEGIN

I'm declaring a local variable because we'll need to get the primary key of the item to update the row if an update has been done. The "IF" statement isn't necessary if you want to update the timestamp when anything changes in the row. However, if you want to update the timestamp only if a specific column (or columns) has changed, list the column(s) to check in the "IF Update()" section.

SELECT
@Item_Pk = Item_Pk
FROM
Deleted
"Deleted" and "Inserted" are two system tables that temporarily contain all the data that was manipulated in the last T-SQL command. For an update, "Deleted" contains all the original data and "Inserted" contains the changed data. Get the primary key out of the "Deleted" table so you know which row's timestamp to update.

UPDATE
Items
SET
ItemEditDate = getDate()
WHERE
Item_Pk = @Item_Pk
END
Now update the row in the original table with the new timestamp using the "getDate()" function and stick on the "END" statement if you used an "IF" statement at the beginning.

Triggers can also be used to prevent specific data from being removed from the database. This is very handy when you don't want someone to inadvertently remove an important row from a table. For example, at our store we have an order table and a gift certificate table in our system. We want the order table to contain the key from the gift certificate table, but we also want to make sure that the key does exist, so we establish a relationship between these tables. However, when a gift certificate isn't used on an order, we still need to insert some valid value so the relationship doesn't throw an error. We use the first row in the gift certificate table as the default key to go in the orders table. We don't want this row to be deleted because it would cause errors in our program. We could use CF to always check this but what if a command isn't sent through CF? It's much more reliable to let the database check this itself. See Listing 5 for the code. Notice the "Rollback Transaction" line. This reverses everything that the previous SQL statement tried to do.

To add a trigger to the database, either take the code in Listing 4 and run it through the Query Analyzer tool or use Enterprise Manager by right-clicking on the table name as illustrated in Figure 1; you'll get the screen shown in Figure 2.

User-Defined Functions (UDFs)
UDFs made their debut in CF 5 and MS-SQL2000. I'll demonstrate a simple T-SQL UDF that's already found in CF but lacking in T-SQL's built-in functions: "Trim()".

T-SQL contains "Left()" and "Right()" functions but lacks a "Trim()" function. With UDFs it's simple to create your own. Here's the code for the "Trim()" function:

CREATE FUNCTION Trim
(@String varchar(200))
RETURNS varchar (200)
AS
BEGIN
RETURN LTrim(RTrim(@String))
END
The line under the "CREATE..." statement tells what type of data will be given to the function. "RETURNS..." tells what type of data will be returned from the function. The actual processing occurs between the "BEGIN" and "END" statements.

To call a UDF in a T-SQL statement you need to prefix it with "dbo.". This lets the database know that it should look for an object in the database with your function's name.

INSERT INTO
Names
(FirstName,LastName)
VALUES
dbo.Trim(@FirstName),
dbo.Trim(@LastName)
Functions can be created through the Query Analyzer or Enterprise Manager (see Figure 3).

Cursors
Sometimes it's necessary to copy data directly from one table to another. You could do it using CF as in Listing 6, using <CFQUERY> as in Listing 7, or using the same T-SQL code in Listing 7 in a stored procedure.

What if you need to add more data or manipulate the data before it's inserted? Cursors are the answer. They allow you to take the result set from one select statement, loop over it, and change data line by line.

Cursor syntax is a little tricky.

DECLARE Cart2Order CURSOR
FAST_FORWARD
FOR
SELECT
CartDetail_Pk,
ItemNumber,
Qty,
UUID
FROM
CartDetail
The first line of the code gives the cursor a name. The second line tells what type of cursor it is. "FAST_FORWARD" means the cursor can only scroll from the first to the last record and that the data within the cursor can't be updated. For a full list of cursor options, check the "cursor, types" section of the SQL documentation. "FOR SELECT..." defines the recordset retrieved by the cursor.

OPEN Cart2Order
To use the cursor you need to open it.

DECLARE
@CartDetail_Pk [int],
@ItemNumber [int],
@Qty [int],
@UUID char(35)
Declare all your local variables at the beginning of a stored procedure or as needed. I define local variables that will be used only within a cursor at the beginning of the cursor so the rest of the code is cleaner.

FETCH NEXT FROM Cart2Order

INTO
@CartDetail_Pk,
@ItemNumber,
@Qty,
@UUID

"FETCH NEXT...INTO" takes the first row of the result set and puts it into the local variables.

WHILE @@fetch_status <> -1
BEGIN
When you create a cursor, the "@@Fetch_Status" variable provides information about it. By checking the status after each loop, we can tell when to quit looping. The cursor returns a "-1" value when the cursor is closed. A "FAST_FORWARD" cursor automatically closes itself when it reaches the last row, so this check will stop attempts to loop beyond the result set.

SELECT
@User_Pk = @User_Pk
FROM
Users
WHERE
UserID = @UserID
This is the first part of the processing. Check if this user, as identified by a unique UUID, exists. If the user does, go ahead and move the item to the order. If not, create the user and then add the item to the order. In real life I'd recommend creating the user before starting work on the cart. I'm doing it this way to demonstrate using "IS NULL" instead of "@@Rowcount". Instead of getting a recordset, set a local variable. This is useful and can prevent a second trip to the table for more data.

IF @User_Pk IS NULL
BEGIN
(Create the user)

SET @User_Pk = SCOPE_IDENTITY()
END

Rather than seeing if you re-ceived any rows using "@@Rowcount", check if "@User_Pk" has a value. If it does, you already have the data you need. If it doesn't, skip creating a user. "Scope_Identity()" provides us with the key generated by our insert statement.

INSERT INTO
OrderDetail
(ItemNumber,
Qty,
User_Pk)
VALUES
@ItemNumber_Pk,
@Qty,
@User_Pk
If you used "@@Rowcount" instead of setting the local variable "@User_Pk", you'd have to make a second request from the database to get the value for @User_Pk.

DELETE
CartDetail
WHERE
CartDetail_Pk = @CartDetail_Pk

FETCH NEXT FROM Cart2Order
INTO
@CartDetail_Pk,
@Qty,
@User_Pk

END

After you finish processing each row, get the next row to run the loop again.

DEALLOCATE Cart2Order
When you're finished with the cursor, the line above removes it from memory. Always end your code this way to avoid cluttering your database memory with unnecessary data.

Summary
In this article I've shown how to expand the use of the database to improve site performance, cut down on network traffic, and safeguard data. In the next article I'll show how to debug stored procedures and cursors, and also explain some gotchas when trying to do math with null values.

More Stories By Ian Rutherford

I have been working with CF for two years and am currently the designer of CatholicStore.com and Catholicliturgy.com. I have been working with SQL for two years and started working with stored procedures about two months ago as we began an update of CatholicStore.com. Both sites are built using the Fusebox methodology.

I graduated from the University of Dallas in 1996 with a Political Philosophy degree which explains why I do web programming.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.