Welcome!

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.

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.


@ThingsExpo Stories
Imagine if you will, a retail floor so densely packed with sensors that they can pick up the movements of insects scurrying across a store aisle. Or a component of a piece of factory equipment so well-instrumented that its digital twin provides resolution down to the micrometer.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. 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 settle...
BnkToTheFuture.com is the largest online investment platform for investing in FinTech, Bitcoin and Blockchain companies. We believe the future of finance looks very different from the past and we aim to invest and provide trading opportunities for qualifying investors that want to build a portfolio in the sector in compliance with international financial regulations.
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
We are given a desktop platform with Java 8 or Java 9 installed and seek to find a way to deploy high-performance Java applications that use Java 3D and/or Jogl without having to run an installer. We are subject to the constraint that the applications be signed and deployed so that they can be run in a trusted environment (i.e., outside of the sandbox). Further, we seek to do this in a way that does not depend on bundling a JRE with our applications, as this makes downloads and installations rat...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...