Find Inefficient T-SQL Stored Procedures

Freshness Warning
This post is more than 2 years old. Please bear in mind its age when reading.

The following is a stored procedure you can use when you want to quickly identify procedures in your SQL Server database which are taking up excessive CPU time.

The script returns 3 recordsets:

  • The number of active connections by database name, with login name and hostname
  • All stored procedures with execution count and total/average CPU times
  • All stored procedures with average and total elapsed time
CREATE PROCEDURE [dbo].[procProcessTimes]

AS

SELECT DB_NAME(dbid) as DBName, COUNT(dbid) as NumberOfConnections, loginame as LoginName , Hostname
FROM    sys.sysprocesses 
WHERE     dbid > 0 
GROUP BY     dbid, loginame, Hostname

SELECT DB_NAME(st.dbid) DBName
      ,OBJECT_SCHEMA_NAME(st.objectid,dbid) SchemaName
      ,OBJECT_NAME(st.objectid,dbid) StoredProcedure
      ,max(cp.usecounts) Execution_count
      ,sum(qs.total_worker_time) total_cpu_time
      ,sum(qs.total_worker_time) / (max(cp.usecounts) * 1.0)  avg_cpu_time 
 FROM sys.dm_exec_cached_plans cp join sys.dm_exec_query_stats qs on cp.plan_handle = qs.plan_handle
      CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
 where DB_NAME(st.dbid) is not null and cp.objtype = 'proc'
 group by DB_NAME(st.dbid),OBJECT_SCHEMA_NAME(objectid,st.dbid), OBJECT_NAME(objectid,st.dbid) 
 order by sum(qs.total_worker_time) desc

SELECT DB_NAME(st.dbid) DBName
      ,OBJECT_SCHEMA_NAME(objectid,st.dbid) SchemaName
      ,OBJECT_NAME(objectid,st.dbid) StoredProcedure
      ,max(cp.usecounts) execution_count
      ,sum(qs.total_elapsed_time) total_elapsed_time
      ,sum(qs.total_elapsed_time) / max(cp.usecounts) avg_elapsed_time
 FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) st
   join sys.dm_exec_cached_plans cp on qs.plan_handle = cp.plan_handle
  where DB_NAME(st.dbid) is not null and cp.objtype = 'proc'
 group by DB_NAME(st.dbid),OBJECT_SCHEMA_NAME(objectid,st.dbid), OBJECT_NAME(objectid,st.dbid) 
 order by sum(qs.total_elapsed_time) desc
I'm running the 39th BMW Berlin Marathon on 30th September 2012 for the British Lung Foundation, who are currently funding research on the prevention of lung damage in COPD and many other areas related to lung disease.

I'm participating with my sister Claire Kewney and, on behalf of the charity, would appreciate even the smallest donation. My own JustGiving page is here, our team page is here.

if you're in the UK, you can also donate using your mobile phone by texting NKEW82 £5 (or any amount) to 70070. Your donation will be appreciated!

Comments

Your Comment
Your Name
E-mail Address (This won't be published)
Website URL

You can manage your Kewney.com account by logging in. [ Log On ]