SQL查询性能统计消息多次返回

Posted

技术标签:

【中文标题】SQL查询性能统计消息多次返回【英文标题】:SQL query performance statistics messages returned multiple times 【发布时间】:2016-03-10 09:57:45 【问题描述】:

我在 SQL Server 管理工作室上运行此查询 1,看到它返回了 3 条消息,但当内部存储过程有近 10 到 20 条来自统计信息的消息时也是如此。发生了什么,为什么我会看到它们?

SET STATISTICS IO,TIME ON;
GO
    SELECT [UserId]
         ,[UserType]
         ,[CreateDT]
         ,[EffectiveDT]
       FROM [dbo].[People] ORDER BY [UserId]
SET STATISTICS IO,TIME OFF;
GO

我收到的消息如下

SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.
SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.
Table 'People'. Scan count 1, logical reads 155, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 143 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 143 ms.

查询的总耗时是 143ms + 143ms 吗?

【问题讨论】:

【参考方案1】:

见下文

set statistics time on
select * from test
set statistics time off

输出:

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 264 ms..

现在添加打印语句和一些变量

set statistics time on

print' statistics time '
declare @a int
set @a =1

select * from test
set statistics time off

输出:

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 1 ms.

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 1 ms.

(59 row(s) affected)

(1 row(s) affected)

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 264 ms.

上面这段代码的总执行时间是1+1+264。

希望这有助于它的工作原理

【讨论】:

这是否意味着在您的情况下执行查询所花费的总时间是 1 + 1 + 264

以上是关于SQL查询性能统计消息多次返回的主要内容,如果未能解决你的问题,请参考以下文章

SQL 多选一个字段值只选一次 和多次从表里查询但查的字段较少 相比哪个性能更好?为啥?

如何进行SQL性能优化

通过手动创建统计信息优化sql查询性能案例

sql server 统计信息

SQL 查询卡在统计状态

Oracle 中最耗时的 5 个 SQL 查询