从视图查询在 SSMS 中需要几分钟,但在 Excel 中超时。如何诊断?

Querying from a view takes minutes in SSMS, but times out in Excel. How to diagnose?

我有一组针对视图的查询,运行 在 SSMS 中很好。他们在 SSMS 中最多用了 3 分钟就完成了,而在 Excel(通过 Power Query)中并没有那么长。我最近在它们所依赖的一个视图中添加了更多 PARTITION BYs,现在,也许巧合的是,它们现在在 SSMS 中并没有慢很多,但它们现在在 Excel 中查询需要很长时间,以至于它超时。

此处的查询太大 post。我的问题只有一个:我如何开始诊断此类问题并找到造成这种巨大差异的原因?

此行为 - “在 SSMS 中速度快,在应用程序中速度慢”可能是由 SQL 服务器的一项名为 Parameter sniffing 的功能引起的。

SQL Server uses a process called parameter sniffing when it executes stored procedures that have parameters. When the procedure is compiled or recompiled, the value passed into the parameter is evaluated and used to create an execution plan. That value is then stored with the execution plan in the plan cache. On subsequent executions, that same value – and same plan – is used.

此过程适用于任何查询,而不仅仅是存储过程。此外,引擎不仅“嗅探”参数值,还“嗅探”基数估计(表有多少行)。这意味着即使您的查询没有参数,我下面的建议也可能有所帮助。

Erland Sommarskog 的文章 Slow in the Application, Fast in SSMS 更详细地解释了这个领域和其他相关领域。无论我的以下建议是否对您有帮助,我都强烈建议您阅读它。

希望您使用SQL Server 2008 或更高版本。首先,只需尝试将 OPTION(RECOMPILE) 添加到您的查询中,如下所示:

SELECT * 
FROM [MY_FINAL_VIEW] 
OPTION(RECOMPILE)
;