设置作业以监视SQL Server的CPU使用情况

时间:2018-08-23 21:41:35

标签: sql-server tsql sql-server-2008 sql-server-2008-r2 sql-job

我想创建一个作业,以在SQL Server使用超过50%的CPU时发出警报。我正在使用几个脚本来获取SQL Server的CPU使用率并获取SQL上当前正在运行的查询。我想以一种方式安排作业,以便当SQL达到基于第一个查询的SQL达到CPU的50%时发出警报,并使用第二个查询将当前正在执行的查询结果发送到电子邮件/ excel中,以便我们至少获得最少的信息转发并知道哪些查询占用了大部分CPU,还请建议我采用其他任何方式以较低的复杂度执行此操作。使用的SQL Server是2008和2008R2 Enterprise

    --Query for last 15minutes SQL Cpu Utiliaztion
DECLARE @ms_ticks_now BIGINT

SELECT @ms_ticks_now = ms_ticks
FROM sys.dm_os_sys_info;

SELECT TOP 15 record_id
    ,dateadd(ms, - 1 * (@ms_ticks_now - [timestamp]), GetDate()) AS EventTime
    ,SQLProcessUtilization
    ,SystemIdle
    ,100 - SystemIdle - SQLProcessUtilization AS OtherProcessUtilization
FROM (
    SELECT record.value('(./Record/@id)[1]', 'int') AS record_id
        ,record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle
        ,record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization
        ,TIMESTAMP
    FROM (
        SELECT TIMESTAMP
            ,convert(XML, record) AS record
        FROM sys.dm_os_ring_buffers
        WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
            AND record LIKE '%<SystemHealth>%'
        ) AS x
    ) AS y
ORDER BY record_id DESC


--Query to get current executing queries:
SELECT 
    r.session_id
    ,st.TEXT AS batch_text
    ,SUBSTRING(st.TEXT, statement_start_offset / 2 + 1, (
            (
                CASE 
                    WHEN r.statement_end_offset = - 1
                        THEN (LEN(CONVERT(NVARCHAR(max), st.TEXT)) * 2)
                    ELSE r.statement_end_offset
                    END
                ) - r.statement_start_offset
            ) / 2 + 1) AS statement_text
    ,qp.query_plan AS 'XML Plan'
    ,r.*
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st
CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS qp
ORDER BY cpu_time DESC

0 个答案:

没有答案