简体   繁体   English

SQL Server 性能:删除/插入与选择/更新

[英]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.我有一个非常大的数据库,只有 60 多场演出,有许多包含数百万行的表。 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)从表中删除 person=123(删除大约 200 行)

Then I re-insert the updated data (again, 200 rows).然后我重新插入更新的数据(再次插入 200 行)。 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#).如果我要进行更新而不是插入,我必须先选择行(我在 c# 中使用 ORM)。

tl;dr I am just wondering, simple question, what is more cost effective. tl;dr 我只是想知道,简单的问题,什么更划算。 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?您将如何处理 UPDATE 的基数差异? Ie. IE。 person=123 has 200 rows to delete, but only 199 to insert. person=123 有 200 行要删除,但只有 199 行要插入。 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.您最好的方法应该是使用MERGE语句和带有新值的表值参数 Of course, no ORM can handle this, but you mention 'performance', and the terms 'performance' and 'ORM' cannot be used in the same sentence...当然,没有 ORM 可以处理这个,但是你提到了“性能”,并且术语“性能”和“ORM”不能用在同一个句子中......

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.您可以测试这两种方法并在 SQL Profiler 中观察结果,但 9/10 更新会更快。

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.可能需要注意的是,我会确保对 person 键进行索引,这样您就不会进行完整的表扫描来查找受影响的记录。

Finally, as @Mundu say, you may want to do this using a parametrized query via ADO.NET instead of the ORM.最后,正如@Mundu 所说,您可能希望通过 ADO.NET 而不是 ORM 使用参数化查询来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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