digicidal
asked on
Best solution to SQL insert-retrieve query function. (Tacobell777 - but others too!)
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. :)
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. :)
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
yes you are better of using SCOPE_IDENTITY()
you guys are robbing my points!!!! ;-))
you guys are robbing my points!!!! ;-))
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.