如何确定哪个查询在SSMS 2014中更有效

时间:2016-04-15 16:11:04

标签: sql-server sql-server-2008 ssms-2014

使用SSMS,如何确定哪个查询更有效?我更喜欢A,但我被告知子查询对Transmission中的每一行执行一次,因此B是首选。

A

Update t set t.transmission_status_id = 
(select transmission_status_id from transmission_status where code = 'TRANSLATED')
from transmission t
where t.transmission_status_id = 
(select transmission_status_id from transmission_status where code = 'RECEIVED')

declare @transmission_status_TRANSLATED INT = (select transmission_status_id from transmission_status where code = 'TRANSLATED')
declare @transmision_status_RECEIVED INT = (select transmission_status_id from transmission_status where code = 'RECEIVED')

Update t set t.transmission_status_id = @transmission_status_TRANSLATED
from transmission t 
where t.transmission_status_id = @transmision_status_RECEIVED

编辑:这是使用SET STATISTICS ON的统计数据:

一个。

Table 'transmission_status'. Scan count 1, logical reads 2, physical reads 0, 
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'transmission_status'. Scan count 1, logical reads 2, physical reads 0, 
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'transmission'. Scan count 1, logical reads 778, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'transmission'. Scan count 1, logical reads 778, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'transmission_status'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

所以,据我所知,效率没有差别。

编辑2:所以我现在得到它:由于子查询不是correlated子查询,它只执行一次。 https://en.wikipedia.org/wiki/Correlated_subquery(感谢链接的@destination_data。)

2 个答案:

答案 0 :(得分:2)

这需要检查实际的执行计划,但我怀疑它们将是相同的。这些子查询应该只执行一次,因为它们没有相关性,引擎非常适合看到那些东西。

如果您真的想了解详情,请查看Grant Fritchey的这本免费电子书。 https://www.red-gate.com/library/sql-server-execution-plans-2nd-edition

答案 1 :(得分:0)

与SSMS中的查询进行比较的方法:

在SSMS中,在单个选项卡上包含两个查询。选择“查询”菜单,然后选择“包含客户端统计信息”

注释掉其中一个查询,然后运行另一个查询。选择“客户统计”标签并查看统计信息。

现在注释掉另一个查询,取消注释第一个查询,然后再次运行。这两个统计信息都将显示在“客户端统计信息”选项卡中,您可以轻松查看哪个更有效。