Just another day I was playing with my query which I posted earlier SQL SERVER – 2008 – 2005 – Find Longest Running Query – TSQL and I found that I got error devide by zero. I have fixed this error in following query as well I have updated query to return time in millisecond instead of microsecond. Jerry Hung has also posted similar solution in comments of original article.
I strongly suggest to read original article to now more about introduction and learn about DBCC command which clears cache.
SELECT DISTINCT TOP 10
t.TEXT QueryName,
s.execution_count AS ExecutionCount,
s.max_elapsed_time AS MaxElapsedTime,
ISNULL(s.total_elapsed_time / 1000 / NULLIF(s.execution_count, 0), 0) AS AvgElapsedTime,
s.creation_time AS LogCreatedOn,
ISNULL(s.execution_count / 1000 / NULLIF(DATEDIFF(s, s.creation_time, GETDATE()), 0), 0) AS FrequencyPerSec
FROM sys.dm_exec_query_stats s
CROSS APPLY sys.dm_exec_sql_text( s.sql_handle ) t
ORDER BY s.max_elapsed_time DESC, ExecutionCount DESC,
GO
Reference : Pinal Dave (http://blog.SQLAuthority.com)





Nice blog with huge information about SQL SERVER. I just found your blog, and really enjoyed reading this post.
Hello,
Just delete the “,” before the GO command.
Thanks
Again one easy to understand and nice blog based on SQL server….
This is for 2005 but what to do for sql server 2000?
I think we can use SQL profiler for that ,we can also check the using activity monitor,sysprocess,sp_locks , sp_who2 .
Oops, don’t even know my name was mentioned, but thanks Pinal
Just want to share, came over this article 02/20 “usp_Worst_TSQL”
It’s a powerful script to find worst performing queries, with parameters
http://www.databasejournal.com/features/mssql/article.php/3802936/Finding-the-Worst-Performing-T-SQL-Statements-on-an-Instance.htm
I have multiple user databases. How would I modify the query to add a column showing which database the query is executing against?
@Wayne,
Check This.
SELECT DISTINCT TOP 10
db_name(dbid) DatabaseName, — Added
t.TEXT QueryName,
s.execution_count AS ExecutionCount,
s.max_elapsed_time AS MaxElapsedTime,
ISNULL(s.total_elapsed_time / 1000 / NULLIF(s.execution_count, 0), 0) AS AvgElapsedTime,
s.creation_time AS LogCreatedOn,
ISNULL(s.execution_count / 1000 / NULLIF(DATEDIFF(s, s.creation_time, GETDATE()), 0), 0) AS FrequencyPerSec
FROM sys.dm_exec_query_stats s
CROSS APPLY sys.dm_exec_sql_text( s.sql_handle ) t
ORDER BY s.max_elapsed_time DESC, ExecutionCount DESC
I dont know why database name is returned NULL some times… Check this throughly before you use it…
~ IM.
Hi ,
Is there any method to get the host name with this query?
I am not able to connect this with sysprocesses to get the hostname.
Please help.
Hi,
Please add the hostname with this query.
I am not able to join sysprocess for hostname with this query.