views:

5916

answers:

4

I'm trying to do the classic Insert/Update scenario where I need to update existing rows in a database or insert them if they are not there.

I've found a previous question on the subject, but it deals with stored procedures, which I'm not using. I'd like to just use plain SQL SELECT, INSERT and UPDATE statements, unless there's something better available (the MERGE statement isn't available in SQL Server 2005).

I guess my general idea is this:

If the row is found
  update
else
  insert

As for checking for a row's existence, how expensive is it to do a SELECT statement before calling an UPDATE or an INSERT? Or is it better to just try an UPDATE, check for the number of rows affected, and then do an INSERT if the rows affected is 0?

+7  A: 

The most efficient way is to do the UPDATE, then do an INSERT if @@rowcount is zero, as explained in this previous answer.

Sören Kuklau
Thanks, that did it! That question didn't come up in my search...
Paul Fedory
A: 

(First of all - I would not try to avoid stored procedures, if there is no strong reason. The give a good benefit in most cases.)

You could do it this way:

  • create a (temporary) table
  • fill in your rows
  • run a INTERSECT that identifies the extisting rows
  • update your table with them
  • run a EXCEPT that identifies the new rows
  • run an insert with these elements
  • drop/clear your (temporary) table

This will probably run faster, if you are inserting/updating large amounts of rows.

MrFox
A: 
Craig Norton
Plenty of reasons. Just off the top of my head: 1) you could have a trigger that acts on DELETE that you don't want fired in this case. 2) If your table uses identities, which it likely should, you'd get entirely new ones. 3) SQL Server can't optimize as easily.
Sören Kuklau
A: 

Completely understand that your post was titled "SQL Server 2005" but just wanted to throw out something to look forward to if/when you upgrade to SQL 2008. Microsoft has added a new MERGE statement which will give you the ability to code one DML statement that does both the update and insert. It's pretty cool. I've yet to compare performance and I/Os but it's just great to have another tool in your toolbox.

esabine
I've found that the SQl Management studio 2008 has soem problems with SQLServer 2000. Still no problem if you don't need to go back that far.
Craig Norton
Before the August RTM we did have problems connecting to SQL 2000 instances if the user was not a sysadmin. Luckily that was fixed in the RTM version. What other problems have you seen?
esabine