开发者

SQL Server Performance: Delete/Insert Vs Select/Update

开发者 https://www.devze.com 2023-04-11 19:31 出处:网络
I have a very large database, little over 60 gigs, with many tables with millions of rows.I am getting some timeout errors, so I am rethinking some of my code design.

I have a very large database, little over 60 gigs, with many tables with millions of rows. I am getting some timeout errors, so I am rethinking some of my code design.

Currently, my pseduo code is like this:

delete from table where person=123 (deletes about 200 rows)

Then I re-insert the u开发者_StackOverflowpdated data (again, 200 rows). The data is always different, as it's time sensitive.

If I was to do an update, instead of insert, I'd have to select the row first (I'm using an ORM in c#).

tl;dr I am just wondering, simple question, what is more cost effective. Select / Update or Delete/Insert?


  1. If you update any column that is part of the clustered index key then your update is handled internally as a delete/insert anyway

  2. How would you handle the difference in cardinality with an UPDATE? Ie. person=123 has 200 rows to delete, but only 199 to insert. Update would not be able to handle this.

Your best approach should be to use a MERGE statement and a table valued parameter with the new values. Of course, no ORM can handle this, but you mention 'performance', and the terms 'performance' and 'ORM' cannot be used in the same sentence...


With Delete/Insert, you will be writing to the database twice. One time to delete and one time to insert. You will also be logging both of those transactions separately, unless you are properly wrapping the entire process in a single transaction.

You could test both methods and watch the results in SQL Profiler, but 9/10 Update will be quicker.

Could of cavets, I'd make sure the person key is indexed so that you are not doing a complete table scan to find the affected records.

Finally, as @Mundu say, you may want to do this using a parametrized query via ADO.NET instead of the ORM.

0

精彩评论

暂无评论...
验证码 换一张
取 消