SQL Tips by Namwar Rizvi

May 18, 2007

List the most time consuming queries on your SQL Sever 2005

Filed under: New Features,SQL Server 2005,tips,TSQL — namwar @ 10:20 PM

Ask any DBA, what is the most critical information he wants to know before starting optimization? Answer will be the list of most time consuming queries on the SQL Server. With many other goodies in SQL Server 2005, another good thing is that this information is now very easily available by dynamic management views. Following is the query which will return you the list of queries sorted by average CPU time in descending order, so the first one is the most time consuming query and so on.
This query is originally available at:
http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/sqlos/default.mspx?mfr=true

SELECT
qs.total_worker_time/qs.execution_count as [Avg CPU Time],
SUBSTRING(qt.text,qs.statement_start_offset/2,
(
case
when qs.statement_end_offset = 1 then len(convert(nvarchar(max), qt.text)) * 2
else qs.statement_end_offset end qs.statement_start_offset)/2
) as query_text,
qt.dbid,
dbname=db_name(qt.dbid),
qt.objectid

FROM sys.dm_exec_query_stats qs
cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt
ORDER BY
[Avg CPU Time] DESC

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: