Log Sql server存储过程的开始和结束时间

时间:2011-07-20 13:13:06

标签: sql-server logging stored-procedures

我已经重载了SQL Server,我想进行一些优化。

为此,我想获得一些关于被调用存储过程的开始和结束时间的统计信息。

是否有任何系统表或其他项目,我可以从中获取此信息?

3 个答案:

答案 0 :(得分:4)

SELECT 
    [procedure] = QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))
        + '.' + QUOTENAME(OBJECT_NAME([object_id])),
    last_execution_time,
    avg_execution_time = CONVERT(DECIMAL(30,2), total_worker_time * 1.0 / execution_count),
    max_worker_time
FROM sys.dm_exec_procedure_stats
WHERE database_id = DB_ID()
ORDER BY avg_execution_time DESC;

答案 1 :(得分:2)

查看DM Objects - Sys.dm exec query stats

或来自http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=159011

  

...如果你在sql 2008或更高版本上运行。 .....

SELECT 

COALESCE(DB_NAME(t.[dbid]),'Unknown') AS [DB Name],
ecp.objtype AS [Object Type],
t.[text] AS [Adhoc Batch or Object Call],
SUBSTRING(t.[text], (qs.[statement_start_offset]/2) + 1,
((CASE qs.[statement_end_offset]
WHEN -1 THEN DATALENGTH(t.[text]) ELSE qs.[statement_end_offset] END
- qs.[statement_start_offset])/2) + 1) AS [Executed Statement]
,qs.[last_execution_time] AS [Last Exec Time]
,qs.[creation_time] AS [Creation Time]

FROM sys.dm_exec_query_stats AS qs
    JOIN sys.dm_exec_cached_plans ecp 
            ON qs.plan_handle = ecp.plan_handle
            CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS t
where
    ecp.objtype = 'Proc'

order by [Last Exec Time] desc

答案 2 :(得分:1)

您可以手动创建自己的系统日志表,然后在存储过程的开头插入新行,然后在结尾处更新它:

INSERT INTO systemLog (proc,start) VALUES ('My Proc',GETDATE())
SELECT @logid = SCOPE_IDENTITY()

--Do stuff here

UPDATE systemLog SET enddate = GETDATE() WHERE logid = @logid

这样做的好处是,如果存储过程失败,它将不会更新系统日志enddate