SQL Alert when stored procedure executes for too long

前端 未结 6 1455
旧时难觅i
旧时难觅i 2021-01-13 07:32

I would like to set up a SQL Server 2008 Alert to notify me when any procedure executes for 1 second or longer (just an example).

Any ideas?

EDIT:

Ok

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 07:56

    You could use a monitoring software like Nagios to periodically count the number of slow queries in your database.

    I personally use the following query with the excellent PRTG. I set it to send me an email each time I have more than 5 queries with an execution time greater than 3 seconds each, or when the slowest query takes longer than 10 seconds:

    SELECT total_elapsed_time / execution_count / 1000000 avg_elapsed_time, execution_count, creation_time, last_execution_time, 
    SUBSTRING(st.text, (qs.statement_start_offset/2) + 1, ((CASE statement_end_offset WHEN -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS statement_text
    FROM sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
    WHERE total_elapsed_time / execution_count / 1000000 >= 3  -- filter queries that takes > 3 seconds
    AND CHARINDEX('dm_exec_query_stats', st.text) = 0   -- In case this query is slow, we don't want it in the result set!
    ORDER BY total_elapsed_time / execution_count DESC;
    

    Disclaimer: this query is based on https://stackoverflow.com/a/820252/638040

    Now if you want to monitor your Stored Procedures, then just use sys.dm_exec_procedure_stats instead of sys.dm_exec_sql_text (also remove the field creation_time from the selection and tweak the SUBSTRING on st.text)

提交回复
热议问题