在变量中捕获 SQL 统计时间

Capturing SQL Statistics Time In A Variable

我想通过大量 运行ge 可变选项对一些高级查询进行一些自动化 SQL 分析。我希望做的是类似于以下内容

set statistics io on
set statistics time on

select *
from MyTable

set statistics time off
set statistics io off

--Somehow return the statistics for this query back to the calling C# code
-- so that I can log it for displaying in a report among other queries

我已尝试使用以下内容,但我不确定如何找到我的 运行 查询的查询句柄以提取所需的执行时间

select * from sys.dm_exec_query_stats

所以我的问题确实有 2 个解决方案。 1) 是否可以简单地捕获 statistcs return 消息? 2) 或者是否可以找到我的 sql 查询句柄,以便我可以查询 dm_exec_query_stats table?

我还应该提到我考虑过执行以下操作,但我希望有一个更完整的解决方案。

declare @StartTime datetime = getdate();
Select * from myTable;
declare @Dur datetime = getdate() - @StartTime;

当然,一转到Whosebug我就自己搞定了!

以防将来有人也在寻找这个......这是一个解决方案,您只需在 where 子句中输入 运行 查询,然后返回所有性能指标。请记住时间是微秒而不是毫秒

SELECT *
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
where st.text = 'Your Query Here'