Sign Doug's SOTR Petition!

Sign Doug's petition to his boss and help send him to Scotch on the Rocks in 2012!
Recent Entries
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
You may also be interested in...
Web Hosting
best web hosting - top web hosting sites, thetop10bestwebhosting.com

Czech your Page Rank!
Check Page Rank of any web site pages instantly:
This free page rank checking tool is powered by Page Rank Checker service
Surf's Up!
Visit Egosurf.org and massage YOUR web ego!
My Score: 9,001
Doug's Books

Read (and recommend)

  • Men are from Mars, Women are from Venus
  • The Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations
  • Blink: The Power of Thinking Without Thinking
  • Head First Design Patterns
  • Transact-SQL Programming
  • What's So Amazing About Grace?
  • Just So Stories (Rudyard Kipling collection)

Reading

  • Prayer: Does it Make Any Difference?
  • Data Mining (Practical Machine Learning Tools and Techniques)
<< February, 2012 >>
SMTWTFS
1234
567891011
12131415161718
19202122232425
26272829
Search Blog

Recent Comments
Re: Basic Ajax Select List Filter in PHP (by opineemia at 2/02 8:47 PM)
Re: PHP vs COLDFUSION (by dougboude at 1/24 9:47 AM)
Re: PHP vs COLDFUSION (by WhatTheHeck at 1/23 7:03 PM)
Re: Recursive Functions in ColdFusion (by Marty McGee at 1/22 1:01 PM)
Re: SQL Forward Engineering with Visio 2003 Professional (by Rama at 1/10 11:05 AM)
Re: PHP Export to Excel Snippet (by rasha at 1/10 1:55 AM)
Re: Fredrick "French" Fry (by Picky eater at 1/09 2:21 PM)
Re: Disappearing IE Popup Window During Save/Open Dialog (by Vivekanand at 1/06 12:51 AM)
Re: Just What IS a 'Service Layer', Anyway? (by Ashishkumar Haldar at 1/05 7:49 AM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by ranjit sachin at 12/20 6:22 AM)
Re: Recursive Functions in ColdFusion (by Jason at 12/15 12:13 PM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by kt at 12/08 3:47 AM)
Re: PayPal IPN Coldfusion CFC (by Guest at 11/28 6:11 PM)
Re: SQL Forward Engineering with Visio 2003 Professional (by freddy villamil at 11/09 2:49 PM)
Re: Finally Found a Use for CFTHREAD (by criclebrava at 11/09 1:23 PM)
Re: Finally Found a Use for CFTHREAD (by assisisowsfub at 11/07 10:37 PM)
Re: IRRITATING CF QUERY ERROR AND SOLUTION (by dougboude at 10/10 10:48 AM)
Re: Using Google as your CF Mail Server (by hlharkins at 10/09 10:24 AM)
Re: IRRITATING CF QUERY ERROR AND SOLUTION (by Peter Boughton at 10/07 3:15 PM)
Re: My Thoughts on the Current Presidential Contenders (by dougboude at 9/23 12:21 PM)
Categories
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

17 May 2010
CONDITIONAL INSERT IN A SINGLE QUERY

Ever had the need to insert a record, but only wanted to do so if the record doesn't already exist? Typically the first approach to this is two queries: one to check for the existence of the values you want to insert, the second to peform that insert IF the first query returned no records. Well, I was in such a spot today, but hated the idea of having to hit the db twice to perform a conditional insert. Though I'm sure I'm not the first one to come up with this approach, I thought I'd share it in case it helps someone else, too.

I'm using a MySQL database, so the query I'm going to demonstrate is written a little bit MySQL-specific, though it is easily translated into MSSQL-speak as well.

The Scenario

Okay, we're looping through a file where each line represents a record. For each of those records, we want to perform an insert IF that record doesn't already exist. Here's how I'm doing it:

 

<cfloop file="C:\Users\doug\Documents\Downloads\R361.TXT" index="L">
 <cfset carrier = rtrim(ltrim(mid(L,1,8))) />
 <cfset claimnum = rtrim(ltrim(mid(L,9,8))) />
 <cfset priorclaim = rtrim(ltrim(mid(L,18,8))) />
 <cfquery name="qryAddClaim" datasource="#dsn#">
  INSERT INTO priorclaim (carrier,claimnum,priorclaim)
  SELECT '#carrier#','#claimnum#','#priorclaim#'
  FROM `priorclaim`
  WHERE not exists
  (
   select * from priorclaim where carrier='#carrier#' and claimnum='#claimnum#' and priorclaim='#priorclaim#'
  )
  LIMIT 0,1
 </cfquery>
</cfloop>

First of all, please know that I highly recommend the use of <cfqueryparam> tags in every place that you see a variable being output. I ommitted that tag in this example for clarity's sake.

Walking through the code, first thing I'm doing is grabbing my values from the current file line. Next, the query. It is obviously an INSERT query using a select statement. The select statement is simply selecting the actual raw values, but ONLY if a record meeting that exact criteria does not already exist. If no record is selected in the WHERE's subquery, the values are inserted; otherwise, nothing happens at all.

Notice my use of the "LIMIT" attribute. This performs the equivalent action of DISTINCT, ensuring that only a single record is returned. Without limiting the results of the SELECT statement, we would get multiple results and would be inserting massive amounts of duplicates. For MSSQL users, simply add the DISTINCT keyword to your SELECT statement, as in "SELECT DISTINCT '#carrier#', '#claimnum#','#priorclaim#' FROM ...."




Posted by dougboude at 1:33 PM | PRINT THIS POST! |Link | 7 comments
Subscription Options

You are not logged in, so your subscription status for this entry is unknown. You can login or register here.

Re: CONDITIONAL INSERT IN A SINGLE QUERY
Here is a similar way of doing that:







if (select count(*) from priorclaim where carrier='#carrier#' and claimnum='#claimnum#' and priorclaim='#priorclaim#') > 0 then
INSERT INTO priorclaim (carrier,claimnum,priorclaim)
SELECT '#carrier#','#claimnum#','#priorclaim#'
end
Posted by Boyan Kostadinov on May 17, 2010 at 4:09 PM

Re: CONDITIONAL INSERT IN A SINGLE QUERY
If you are using Oracle, MERGE is your friend
Posted by Qasim Rasheed on May 17, 2010 at 7:45 PM

Re: CONDITIONAL INSERT IN A SINGLE QUERY
On the MS-SQL side, this works well (and I use it all over the place):

IF NOT EXISTS (
select * from priorclaim where carrier='#carrier#' and claimnum='#claimnum#' and priorclaim='#priorclaim#'
)
BEGIN
INSERT INTO priorclaim (carrier,claimnum,priorclaim)
SELECT '#carrier#','#claimnum#','#priorclaim#'
FROM `priorclaim`
END
Posted by Jason Fisher on May 18, 2010 at 6:47 AM

Re: CONDITIONAL INSERT IN A SINGLE QUERY
@Jason, I could just try it myself to answer the question, but...

Can you execute the above within CFQUERY tags? If so, then dang...I oughta start using a little more T-SQL (or MySQL's equivalent) in my CFQUERIES! :)
Posted by dougboude on May 18, 2010 at 10:14 AM

Re: CONDITIONAL INSERT IN A SINGLE QUERY
@Qasim - Dang, that's pretty nice! Has that been around a long time, or is it something fairly recent? And is Oracle still making you have to maintain those darn sequences separately from the table, like it did back when i used it on a daily basis? I never understood that.... :)
Posted by dougboude on May 18, 2010 at 10:17 AM

Re: CONDITIONAL INSERT IN A SINGLE QUERY
Hey Quasim! Pretty Nice MSSQL Stuff:

Something same like in mysql

that would be nice
Posted by Misty on May 26, 2010 at 9:22 PM

Re: CONDITIONAL INSERT IN A SINGLE QUERY
office 2007 key It is wonderful right here. good research. I've been searched this kind of information for quite a while. thanks
Posted by office 2007 key on November 18, 2010 at 8:06 PM

Name:   Required
Email:   Required your email address will not be publicly displayed.

Want to receive notifications when new comments are added? Login/Register for an account.

Time to take the Turing Test!!!

Six plus Sixteen equals
Type in the answer to the question you see above:

Your comment:

Sorry, no HTML allowed!