TSQL query to find un-used stored procedures

后端 未结 3 886
时光取名叫无心
时光取名叫无心 2020-12-29 06:29

I am trying to track down all stored procedures in a database that have never been used, or that have not been used in many months.

I would like to find a query to s

3条回答
  •  无人及你
    2020-12-29 06:52

    For some reason, my dm_exec_procedure_stats view clears itself out through the day. So I just ran it right now and the earliest execution times are from this morning, but I know we didn't restart SQL this morning or anything.

    Anyway, I wanted to create a proc that I could put into a job to run every hour and capture which procs had run recently. Here is what I did:

    Created a table to log the procs that get executed and their first and last execution times.

    create table ProcsThatExecute (procName varchar(500), firstExecutionTime datetime, lastExecutionTime datetime)
    

    Created a procedure that inserts or updates the ProcsThatExecute table. Run this every hour in a job and after a few days or weeks or months you have a log of which procs get used:

    alter procedure LogProcsThatExecute as begin
    
        --If they don't already exist in this table, add them.
        insert into ProcsThatExecute(procName, firstExecutionTime, lastExecutionTime)
        SELECT p.NAME ProcName, s.last_execution_time, null
        FROM sys.procedures AS p
            LEFT OUTER JOIN sys.dm_exec_procedure_stats AS s ON p.[object_id] = s.[object_id]
        where not exists (
            select 1 from ProcsThatExecute pte where pte.procName = p.name
        ) and last_execution_time is not null
    
    
        --If they do exist in this table, update the last execution time.
        update ProcsThatExecute set lastExecutionTime = s.last_execution_time
        from ProcsThatExecute pte
        inner join sys.procedures AS p on pte.procName = p.name
            LEFT OUTER JOIN sys.dm_exec_procedure_stats AS s ON p.[object_id] = s.[object_id]
        where s.last_execution_time is not null
    
    end
    

提交回复
热议问题