Sql-server – Store time taken to run query in a table

sql server

I am trying to gauge performance across about 300 views with and without some changes. I can write a script easily enough to run every view, but ideally, I wanted to get the time it took for each view to run individually.

I know that you can use SET STATISTICS TIME ON, to get the time, but this would be per-query and would not be easily searchable. Ideally, I wasn't sure if the STATISTICS TIME ON has an output parameter or something, or additionally – if there is a known way to manually time a query's execution so that I can insert it somewhere?

Best Answer

A good start would be to look at the exec_query_stats view. You can get the execution count and total elapsed time and a lot more, but this is only from queries that have been cached.

SELECT dest.TEXT AS [Query],
       (deqs.total_elapsed_time+0.0)/deqs.execution_count average_elapsed_time,
       deqs.*
  FROM sys.dm_exec_query_stats AS deqs
 CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
 ORDER BY 2 DESC

You might want to issue a CHECKPOINT and DBCC DROPCLEANBUFFERS after you've installed your new views to clear the cache.