22

Besides using SQL Server Profiler, is there any way to track which stored procedures are being used, or at least when they were last executed?

Nick Chammas
  • 14,170
  • 17
  • 73
  • 119
DForck42
  • 2,918
  • 3
  • 30
  • 62
  • 4
    You can always look at the plan cache. SQL Server doesn't track this stuff forever because metadata quickly gets large and expensive. – JNK Apr 13 '12 at 18:50

2 Answers2

20

You can look in the plan cache to get a pretty good idea of Stored Procedure usage. Take this query, for instance:

select
    db_name(st.dbid) as database_name,
    object_name(st.objectid) as name,
    p.size_in_bytes / 1024 as size_in_kb,
    p.usecounts,
    st.text
from sys.dm_exec_cached_plans p
cross apply sys.dm_exec_sql_text(p.plan_handle) st
where p.objtype = 'proc'
and st.dbid = db_id('SomeDatabase')
order by p.usecounts desc

This will give you the usecounts of the stored procedures that are cached pertaining to SomeDB.

Note: the plan cache contains the execution plans. This retention of these plans has many factors involved. Whereas this will give you a good idea of what is being used and how often, it's definitely not the running total of stored procedures and how often/when they were executed.

BOL Reference about the Plan Cache

Thomas Stringer
  • 41,128
  • 9
  • 109
  • 152
  • 5
    Remeber this only tells you the sp has been run fairly recently and gives you no information about procs not in here. Things like procs behind quarterly reports are run infrequenty but are being used. So basically, this just gives you a list to research in the applications that hit your db. – HLGEM Apr 13 '12 at 19:07
  • 1
    @HLGEM Precisely. I've tried to make that point clear in my answer. – Thomas Stringer Apr 13 '12 at 19:25
  • Is it possible doing this for a specific datetime range? (e.g. last day/month, etc) ? – Jose Parra Jun 19 '18 at 01:29
  • Note that this query will not return a row for a stored procedure that has been altered and not executed after. – Axel2D May 20 '19 at 14:52
10

You can have a look at this as well as it contains info of last_execution_time of every stored procedure.

    SELECT DB_NAME(database_id)
    ,OBJECT_NAME(object_id,database_id)
    ,cached_time
    ,last_execution_time
    ,execution_count
FROM sys.dm_exec_procedure_stats
Sai Chaitanya M
  • 313
  • 1
  • 3
  • 9
  • There is on caveat to this tho. These stats are only kept since the last database execution. I am busy writing a job that will archive it to a table once a day. – earthling42 May 28 '18 at 09:55
  • @earthling42, did you ever write a job that archived it to a table daily? – Alex Chung Nov 08 '19 at 14:56
  • @Alex Chung - unfortunately never got around to that. Moved onto non MS-SQL projects shortly after the date of this post. Shouldn't be to hard tho? I'd be happy to try to work it out with you if you are interested. – earthling42 Nov 12 '19 at 16:18