| By Ian Rutherford | Article Rating: |
|
| February 5, 2002 12:00 AM EST | Reads: |
25,020 |
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_updateItemTSEach 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.
ON Items
FOR UPDATE
AS
DECLAREI'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.
@Item_Pk intIF Update(ItemMin)
BEGIN
SELECT"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.
@Item_Pk = Item_Pk
FROM
Deleted
UPDATENow 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.
Items
SET
ItemEditDate = getDate()
WHERE
Item_Pk = @Item_Pk
END
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 TrimThe 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.
(@String varchar(200))
RETURNS varchar (200)
AS
BEGIN
RETURN LTrim(RTrim(@String))
END
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 INTOFunctions can be created through the Query Analyzer or Enterprise Manager (see Figure 3).
Names
(FirstName,LastName)
VALUES
dbo.Trim(@FirstName),
dbo.Trim(@LastName)
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 CURSORThe 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.
FAST_FORWARD
FOR
SELECT
CartDetail_Pk,
ItemNumber,
Qty,
UUID
FROM
CartDetail
OPEN Cart2OrderTo use the cursor you need to open it.
DECLAREDeclare 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.
@CartDetail_Pk [int],
@ItemNumber [int],
@Qty [int],
@UUID char(35)
FETCH NEXT FROM Cart2Order"FETCH NEXT...INTO" takes the first row of the result set and puts it into the local variables.INTO
@CartDetail_Pk,
@ItemNumber,
@Qty,
@UUID
WHILE @@fetch_status <> -1When 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.
BEGIN
SELECTThis 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.
@User_Pk = @User_Pk
FROM
Users
WHERE
UserID = @UserID
IF @User_Pk IS NULLRather 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.
BEGIN
(Create the user)SET @User_Pk = SCOPE_IDENTITY()
END
INSERT INTOIf 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.
OrderDetail
(ItemNumber,
Qty,
User_Pk)
VALUES
@ItemNumber_Pk,
@Qty,
@User_Pk
DELETEAfter you finish processing each row, get the next row to run the loop again.
CartDetail
WHERE
CartDetail_Pk = @CartDetail_PkFETCH NEXT FROM Cart2Order
INTO
@CartDetail_Pk,
@Qty,
@User_PkEND
DEALLOCATE Cart2OrderWhen 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.
Published February 5, 2002 Reads 25,020
Copyright © 2002 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
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.
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Adobe Flex Developer Earns $100K in New York City
- Adobe LiveCycle Enterprise Suite 2 for Cloud Computing
- Adobe Betas Target RIAs and Cloud Computing
- Adobe Cans Another 9% of its Workforce
- Moyea DVD4Web Converter V2.0 Converts DVD to FLV Fast and Synchronously with Watermarks
- Adobe Fiddles with its Web Apps
- Adobe & Salesforce Cut Cloud Deal
- Hosting.com Launches ColdFusion 9 in the Cloud
- The Real Time Infrastructure Ultimatum
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Eval JavaScript in a Global Context
- Fig Leaf Software to Exhibit at Government IT Conference & Expo
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Is Microsoft as Free as Open Source?
- Adobe Reader Sued
- The Planet Named “Bronze Sponsor” of Cloud Computing Expo
- Microsoft Expression Web Has Got Game
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Adobe Flex Developer Earns $100K in New York City
- Bruce Chizen Joins Voyager Capital as Venture Partner
- My Top Seven Wishes From Adobe MAX 2009
- The Next Programming Models, RIAs and Composite Applications
- Where Are RIA Technologies Headed in 2008?
- Constructing an Application with Flash Forms from the Ground Up
- AJAX World RIA Conference & Expo Kicks Off in New York City
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Personal Branding Checklist
- Adobe Flex 2: Advanced DataGrid
- Has the Technology Bounceback Begun?
- Building a Zip Code Proximity Search with ColdFusion
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers
- The Asynchronous CFML Gateway
- Web Services Using ColdFusion and Apache CXF


























