SQL Server sp_ExecuteSQL和执行计划

AJM*_*AJM 6 sql t-sql sql-server sql-server-2005 sql-execution-plan

我有一个查询,它在SQL Server Management STudio中是超高速的,并且在sp_ExecuteSQL下运行时超级慢.

这是否与在spExecuteSQL下运行时未执行的执行计划的缓存有关?

Mar*_*ith 8

没有.

您可以使用以下查询查看两个执行计划并进行比较.

SELECT usecounts, cacheobjtype, objtype, text, query_plan, value as set_options
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle) 
CROSS APPLY sys.dm_exec_query_plan(plan_handle) 
cross APPLY sys.dm_exec_plan_attributes(plan_handle) AS epa
where text like '%Some unique string in your query%' 
                                          and attribute='set_options'
Run Code Online (Sandbox Code Playgroud)

sp_executesql版本将有一个objtype"准备好"

  • 为什么执行计划会如此截然不同?例如,我直接从Sql Management Studio查看了我的查询执行计划(需要3秒),而sp_executeSql执行计划(需要5分钟以上).sp_executeSql中的计划完全忽略了直接调用找到的一些键索引.有人可以解释为什么来自管理工作室的调用找到密钥,但通过sp_ExecuteSql调用不会? (3认同)