简体   繁体   中英

How often is Stored Procedure xyz, or Table Valued Function Used – SQL Server 2008 R2

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?

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.]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM