Find the Most Time Consuming Code in your SQL Server Database

This post will demonstrate how to find T-SQL code (SQL Server 2005/2008) that takes the most time to execute. Note that a time consuming code may not necessarily be inefficient; it also depends on the volume of data being processed.

--Top 10 codes that takes maximum time
select top 10 source_code,stats.total_elapsed_time/1000000 as seconds,
last_execution_time from sys.dm_exec_query_stats as stats
cross apply
(SELECT text as source_code FROM sys.dm_exec_sql_text(sql_handle))
AS query_text
order by total_elapsed_time desc

query1

--Top 10 codes that takes maximum physical_reads
select top 10 source_code,stats.total_elapsed_time/1000000 as seconds,
last_execution_time from sys.dm_exec_query_stats as stats
cross apply
(SELECT text as source_code FROM sys.dm_exec_sql_text(sql_handle))
AS query_text
order by total_physical_reads desc

query2

The sys.dm_exec_query_stats is a Dynamic Management view that gives the statistical information's about cached data. The sys.dm_exec_sql_text is the another view that gives actual text of the sql_handle which is in binary format.

The first query sorts data based on descending order of total_elapsed_time and second query by total_physical_reads.

Similarly also read:

and

10 comments:

  1. I see the message: "sql_handle" is not a recognized table hints option. If it is intended as a parameter to a table-valued function, ensure that your database compatibility mode is set to 90

    ReplyDelete
  2. Anonymous,

    The method would work from version 2005 onwards. If you use it make sure the compatibility mode is set to 90

    ReplyDelete
  3. Would total_elapsed_time be the right one a frequently called but quickly executing proc could still appear.

    I'd have thought max_elapsed_time would be a better candidate ?

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. very nice and excellent post,

    www.imran-shafiq.blogspot.com/
    www.hyperlinksolutions.net/

    ReplyDelete
  6. it`s like standart report of sql server "Performance - Top queries by total CPU time"

    ReplyDelete
  7. Please refer the below link also

    http://blog.renjucool.com/2009/11/longest-running-procedures-in-sql.html

    ReplyDelete
  8. thank you very much, this code is very interesting, greetings from Mexico

    ReplyDelete