How often is Stored Procedure xyz, or Table Valued

2019-02-18 15:38发布

We have a number of Views, Stored Procs, Table Values and Scalar functions.

How can we see how often or even how many times these have been called from within SQL Server?

Do we need to edit each one to update a table on each call to get this, or does SQL server keep this information somewhere?

1条回答
可以哭但决不认输i
2楼-- · 2019-02-18 16:03

This is one of Glenn Berry's DMV queries. It counts how many times a cached stored procedure has been executed (filtered by the current database):

SELECT TOP(25) p.name AS [SP Name], qs.execution_count,
ISNULL(qs.execution_count/DATEDIFF(Second, qs.cached_time, GETDATE()), 0) AS [Calls/Second],
qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.total_worker_time AS [TotalWorkerTime],  
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
qs.cached_time
FROM sys.procedures AS p
INNER JOIN sys.dm_exec_procedure_stats AS qs
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.execution_count DESC OPTION (RECOMPILE);

Note: SQL Server keeps info only since last service restart and may also discard info under memory pressure.

Also note that execution count alone does not tell the whole picture. It's often better to identify the most costly queries and improve them. I usually start with highest logical reads (this is another of Glenn's):

SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads], 
qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count, 
ISNULL(qs.execution_count/DATEDIFF(Second, qs.cached_time, GETDATE()), 0) AS [Calls/Second], 
qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count 
AS [avg_elapsed_time], qs.cached_time
FROM sys.procedures AS p
INNER JOIN sys.dm_exec_procedure_stats AS qs
ON p.[object_id] = qs.[object_id]
WHERE qs.database_id = DB_ID()
ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);

[Also, note: you might have processes that are periodically scheduled (say once per month). So, it's not 100% possible to identify stored procedures that are not called using these.]

查看更多
登录 后发表回答