Solved

Best solution to SQL insert-retrieve query function. (Tacobell777 - but others too!)

Posted on 2004-09-29
5
478 Views
Last Modified: 2013-12-24
Been looking forever for a better solution to this than wrapping two queries into a transaction in order to retrieve the new record ID of a row that was just inserted by the query.  Don't want to have to write stored procs for every query I use and hate having to hit SQL twice to just get my new records auto-increment ID value.  This is primarily for TacoBell777, but if anyone else has any really nifty <CFQUERY> tricks or tips here I'll possibly split some points their way too!

BTW - for easy searching by others and for my own referrence, TacoBell777 if you could put a complete example of a short insert-retrieve function here in addition to your other example I'd love it!  Lets say that table TBLMYDATA has the following columns:
RowID (INT, AUTO, PK)
TextCol (NVARCHAR)
NumCol (INT)
BitCol (BIT)

Thanks again for the cool tip and for understanding SQL much better than I do. :)
0
Comment
Question by:digicidal
  • 3
5 Comments
 
LVL 4

Assisted Solution

by:reggi635
reggi635 earned 250 total points
ID: 12187008
No offenses tacobell. Watch out dude you already have some fans in here :-)

My Try :

<cfquery name="qry" datasource="dsn">
 INSERT INTO TBLMYDATA (TextCol, NumCol, BitCol)
      VALUES
      <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#TextCol#">,
      <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#NumCol#">,
      <cfqueryparam cfsqltype="CF_SQL_BIT" value="#BitCol#">
SELECT @@identity AS newID
</cfquery>

<cfoutput>#qry.newID#</cfoutput>

might wanna also check the scope_identity in case u have a trigger.

REGGI
0
 
LVL 9

Author Comment

by:digicidal
ID: 12187579
Hmmm... I was under the (apparently mistaken) belief that you could only guarantee that @@identity would return the correct ID when run in a storedproc - since @@identity is a global and since SQL is a multithreaded app as is CF that you might possibly have someone do an insert on the server in the brief space between the INSERT and the SELECT statements.  In which case the @@Identity would actually return the recordID of the second users INSERT and not the first.

Is this incorrect?  Tacobells solution is the following:

<cfquery ...>
DECLARE @pk INT

INSERT statement here

SET @pk = SCOPE_IDENTITY()

SELECT @pk AS primaryKey
</cfquery>

You actually referrenced that is the last part of your comment... can you (or someone else for that matter) provide evidence or links to conclusively support one method or the other in most cases (I realize that other steps may need to be taken in the case of really complex transactions or triggers on the server side).  You've earned some points already reggi635 - and if Tacobell doesn't choose to comment here I'll award you instead with the whole thing.  I'm really just looking for a discussion on which method is truly better and why.  Particularly in a MS SQL CF MX situation.  I'm just convinced that my old method (transactions with a select MAX(ID) is definitely NOT the best, but I would love to hear some evidence as to why a SCOPE_IDENTITY() method is preferrable or not to @@Identity.
0
 
LVL 17

Expert Comment

by:Tacobell777
ID: 12187640
yes you are better of using SCOPE_IDENTITY()

you guys are robbing my points!!!! ;-))
0
 
LVL 17

Accepted Solution

by:
Tacobell777 earned 250 total points
ID: 12187672
oops, I have to stop just glancing over the questions and actually read them...

<cfquery ...>
INSERT ...

SELECT SCOPE_IDENTITY() AS pkID
</cfquery>

I ussually select it into a variable because I do more than one thing in the same cfquery...

following taken from the online books...

@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.

SCOPE_IDENTITY()
Returns the last IDENTITY value inserted into an IDENTITY column in the same scope. A scope is a module -- a stored procedure, trigger, function, or batch. Thus, two statements are in the same scope if they are in the same stored procedure, function, or batch.
0
 
LVL 17

Assisted Solution

by:Tacobell777
Tacobell777 earned 250 total points
ID: 12187683
PS. MAX is used because it works in more than one database, @@identity and scope_identity() are database specific..
The impact of using it is really not that big... however it is more error prone...

0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Have you ever sent email via ColdFusion and thought of tracking this mail to capture the exact date and time when the message was opened ?  If yes, then this article is for you ! First we need a table user_email with columns user_id , email , sub…
Periodically we have to update or add SSL certificates for customers. Depending upon your hosting plan you may be responsible for the installation and/or key generation. In the wake of Heartbleed many sites were forced to re-key. We will concen…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now