作为Kin脚本的后续内容。这是一个简单的脚本,用于创建一个表来跟踪一段时间内的使用情况,以及一个脚本来定期对其进行更新。
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Create the use table
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CREATE TABLE [dbo].[_ProcedureUseLog](
[ObjectName] [nvarchar](255) NOT NULL,
[UseCount] [int] NULL,
[LastUse] [datetime] NULL,
[LastCache] [datetime] NULL,
CONSTRAINT [PK___PROCEDURE_USE] PRIMARY KEY CLUSTERED
(
[ObjectName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[_ProcedureUseLog] ADD CONSTRAINT [DF_Table_1_References] DEFAULT ((0)) FOR [UseCount]
GO
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Run this periodically to update the usage stats
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DECLARE @UsesTable TABLE
(
ObjectName nvarchar(255),
Executions int,
LastUse datetime,
LastCache datetime
)
INSERT INTO @UsesTable
SELECT p.name, qs.execution_count, qs.last_execution_time, qs.cached_time
FROM sys.procedures AS p LEFT OUTER JOIN
sys.dm_exec_procedure_stats AS qs ON p.object_id = qs.object_id
WHERE (p.is_ms_shipped = 0)
MERGE [dbo].[_ProcedureUseLog] AS [Target]
USING @UsesTable AS [Source]
ON Target.ObjectName = Source.ObjectName
WHEN MATCHED AND
( Target.LastCache <> Source.LastCache)
THEN UPDATE SET
Target.UseCount = Target.UseCount + Source.Executions,
Target.LastCache = Source.LastCache,
Target.LastUse = Source.LastUse
WHEN NOT MATCHED
THEN INSERT (ObjectName, UseCount, LastUse, LastCache)
VALUES (ObjectName, Executions, LastUse, LastCache);
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- This just shows what you've logged so far
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SELECT * FROM [_ProcedureUseLog] ORDER BY UseCount DESC