You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

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.

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

ON Items
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.

@Item_Pk int

IF Update(ItemMin)

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.

@Item_Pk = Item_Pk
"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.

ItemEditDate = getDate()
Item_Pk = @Item_Pk
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:

(@String varchar(200))
RETURNS varchar (200)
RETURN LTrim(RTrim(@String))
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.

Functions can be created through the Query Analyzer or Enterprise Manager (see Figure 3).

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.

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.

@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...INTO" takes the first row of the result set and puts it into the local variables.

WHILE @@fetch_status <> -1
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.

@User_Pk = @User_Pk
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.

(Create the user)


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.

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.

CartDetail_Pk = @CartDetail_Pk



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

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.

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.

IoT & Smart Cities Stories
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Early Bird Registration Discount Expires on August 31, 2018 Conference Registration Link ▸ HERE. Pick from all 200 sessions in all 10 tracks, plus 22 Keynotes & General Sessions! Lunch is served two days. EXPIRES AUGUST 31, 2018. Ticket prices: ($1,295-Aug 31) ($1,495-Oct 31) ($1,995-Nov 12) ($2,500-Walk-in)
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...