简体   繁体   中英

SQL Server Performance: Delete/Insert Vs Select/Update

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 updated 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM