简体   繁体   English

SQL Server - 更新语句中的连接或子查询?

[英]SQL Server - join or subquery in update statements?

Is there a reason to use one of these UPDATE statements over the other with regards to performance? 有没有理由在性能方面使用其中一个UPDATE语句而不是另一个语句?

 UPDATE myTable
 SET    fieldx = 1
 FROM   myTable AS mt
      , myView AS mv
 WHERE  mt.id = mv.id


 UPDATE myTable
 SET    fieldx = 1
 WHERE  id IN ( SELECT id
                     FROM   myView )

They'll probably come out with the same execution plan, meaning there is no difference. 他们可能会提出相同的执行计划,这意味着没有区别。 To confirm, just try each one in SSMS with the "Include Execution Plan" option switched on. 要确认,只需在SSMS中尝试每个,并打开“包含执行计划”选项。

In fact, the one I would go for is: 事实上,我想要的是:

UPDATE mt
SET mt.fieldx = 1
FROM myTable mt
    JOIN myView mv ON mt.ID = mv.ID

I much prefer this syntax. 我更喜欢这种语法。 Though, it too will come out with the same execution plan. 虽然,它也会出现相同的执行计划。

To demonstrate this, I ran a test with each variant of the UPDATE statement. 为了证明这一点,我使用UPDATE语句的每个变体运行了一个测试。 As the execution plans below show, they all came out the same - all perform the same: 正如下面的执行计划所示,它们都是相同的 - 都表现相同:
alt text http://img707.imageshack.us/img707/7801/60422461.png 替代文字http://img707.imageshack.us/img707/7801/60422461.png


alt text http://img683.imageshack.us/img683/7874/41210682.png 替代文字http://img683.imageshack.us/img683/7874/41210682.png


alt text http://img708.imageshack.us/img708/5020/20506532.png alt text http://img708.imageshack.us/img708/5020/20506532.png

While this doesn't speak to performance, I like the first example better so that I could vet it easier without changing the underlying structure of the code. 虽然这不符合性能,但我更喜欢第一个例子,这样我就可以在不改变代码的底层结构的情况下更轻松地审查它。 Notice where and what I put in comments: 请注意我在评论中的位置和内容:

UPDATE myTable 
SET    fieldx = 1
--SELECT *
FROM   myTable AS mt 
      , myView AS mv 
WHERE  mt.id = mv.id

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

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