11

My current project will send queries to an sql server constantly and It may use 100% of the memory or CPU.

  • How can I check if the server is nearing full utilization in a stored procedure so that I can decide whether to execute the queries or not or save some settings in a table so that the following queries can know the workload is high and decide what to do

  • If not, how can I prevent SQL server to reach full utilization?

More information about the case: Right now I know our current test server can process 40-50 queries per second (one specific stored procedure). And now we'll decide how many queries are sent to the server every second. If we set the amount even 1 higher than the expected, in the long run, the queries will eventually fill the virtual memory and out client will have to restart their sql server instance periodically.

Expected Results (For bounty hunters):

@memory_usage float, @cpu_usage float; /* in percentage */

Any ideas are welcomed. Thanks.

4

3 回答 3

7

这样的事情对你有帮助吗?

按 SQL Server 实例监视内存使用情况的脚本

于 2013-02-08T15:51:54.917 回答
5

对于 SQL Server 的任何此类密集使用和对其进行微调的努力,我假设(虚拟)机器专用于 SQL Server。

话虽如此,获取机器当前使用的 CPU 和内存百分比应该可以解决问题:

CREATE PROCEDURE dbo.p_GetSystemUsage
    @cpuUsage float out,   -- % CPU usage
    @memoryUsage float out -- % memory usage
AS
BEGIN
    SET NOCOUNT ON;

    /*
     * % CPU usage
     */

    SELECT TOP 1
        @cpuUsage = 100 - r.SystemIdle
    FROM (
        SELECT
            rx.record.value('(./Record/@id)[1]', 'int') AS record_id,
            rx.record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle
        FROM (
            SELECT 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 rx
        ) AS r
    ORDER BY r.record_id DESC

    /*
     * % memory usage
     */

    SELECT
        @memoryUsage =
            (((m.total_physical_memory_kb - m.available_physical_memory_kb) /
              convert(float, m.total_physical_memory_kb)) *
             100)
    FROM sys.dm_os_sys_memory m
END

需要注意的几点:

  • sys.dm_os_sys_memory是机器物理内存使用的一个很好的来源。它提供了有关机器页面文件使用情况的类似信息。以我的经验,它的信息经常变化——在一秒钟内对其进行多次查询会产生不同的结果。
  • sys.dm_os_ring_buffers是机器 CPU 使用率的一个很好的来源,但它的更新频率并不高 - 从我所看到的每一分钟。如果您需要更多实时信息,也许您可​​以影响这一点。
  • 中的 CPU-usage 值sys.dm_os_ring_buffers是一个整数,但我根据你的规范做@cpuUsage了一个。float由于存储过程使用两个float参数,因此您可以重构 CPU 使用率确定以提供小数部分而不更改其调用者。
于 2013-02-17T22:35:12.413 回答
1

不确定如何在 SQL 中执行此操作,但您始终可以在 C# 中创建一个函数,然后使用 CRL 将其作为存储过程在您的 SQL Server 中可用。

http://msdn.microsoft.com/en-us/library/ms131094.aspx

于 2013-02-17T09:15:52.527 回答