Reply
How do you Insert *OR* Update in SQL?
Old 02-01-2008, 05:08 PM How do you Insert *OR* Update in SQL?
Learning Newbie's Avatar
Moderator

Latest Blog Post:
What’s He Looking At?
Posts: 4,983
Name: John Alexander
This isn't a question where I'm too lazy to look up the answer myself. Here's a sample script:

Code:
If Exists (Select A_Small_Field From MyTable Where Record_ID = ?)
   Update MyTable Set X = ?, Y = ?, Z = ? Where Record_ID = ?
Else
   Insert Into MyTable Values ( ?, ?, ?, ?, ? )
But no matter what happens, you run a very similar query twice. If the system isn't hammered, and the record exists, SQL should cache the row when you run the exists subquery. So it should at least update against memory instead of against the disc. Still, it will have to find that row twice.

Is this really the best way? I mean in terms of performance, I don't mind if it means extra code.

I was thinking I could use a unique constraint with ignore_dup_keys set to on, except that I don't need to just verify a record exists, I actually need to change some of its values.
__________________
4 ways to improve the lives of the "bottom billion"

"HEY YOU KIDS GET OFF MY LAWN!" -John McCain
Learning Newbie is offline
Reply With Quote
View Public Profile
 
When You Register, These Ads Go Away!
     
Old 03-14-2008, 10:55 AM Re: How do you Insert *OR* Update in SQL?
Novice Talker

Posts: 5
No matter what you insert or update, you will need first to find the record where the information to modify is needed.
ludmila is offline
Reply With Quote
View Public Profile
 
Reply     « Reply to How do you Insert *OR* Update in SQL?
 

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off




   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML

 


Page generated in 0.11714 seconds with 13 queries