sql多语句表值函数

问题 ( The Problem )

Checking the many SQL Servers health conditions is one of the DBA basic tasks. Monitoring many servers and databases, day after day can be a very tedious job. There are many aspects to look for when checking the server performance figures. Such aspects include among others: CPU, Read and Write Disk counters, Various memory counters and locks performance counters. The DBA needs a tool that checks the most important counters and output a report that states whether the server is considered to be healthy or not. For every aspect, a counter is chosen to represent it to be included in the overall report.

检查许多SQL Server的运行状况是DBA的基本任务之一。 日复一日地监视许多服务器和数据库是一项非常繁琐的工作。 检查服务器性能指标时,有许多方面需要注意。 这些方面包括: CPU ,读写磁盘计数器,各种内存计数器和锁定性能计数器。 DBA需要一个工具来检查最重要的计数器,并输出报告以表明服务器是否正常。 对于每个方面,都选择一个计数器来表示要包含在整个报告中。

I have chosen here Buffer cache hit ratio counter for memory category, % user time for CPU category, Avg. Disk Sec/Read and Avg. Disk Sec/Write for the Disk category and Avg. Wait Time (ms) for the Locks category. There are many other, good and helpful categories that can be used but I have selected these after referencing many documentation sources.

我在这里为内存类别选择了缓冲区高速缓存命中率计数器,为CPU类别选择了平均 用户时间百分比平均。 磁盘秒/读平均磁盘”类别和“ 平均”的“ 磁盘安全/写入 类别的等待时间(毫秒) 。 还有许多其他的,有用的有用的类别,但是在参考了许多文档资料之后,我选择了这些类别。

建议的解决方案 ( The suggested solution )

The suggested solution for checking the server’s health conditions is to construct a Multi Statement table valued function that will show, in one glance, a comprehensive “Look over” on the most important counters values on the server and show the Resulting result set to the DBA. Each counter is analyzed inside the function according to books, online documentation, best knowledge, and given a good or bad status. If all aspects are ‘Good’ the server status is ‘Healthy’, else then a ‘Sick’ status is given.

建议的用于检查服务器运行状况的解决方案是构造一个多语句表值函数,该函数将一目了然地显示服务器上最重要的计数器值的全面“查找”,并将结果集显示给DBA 。 根据功能,内部文档,最佳知识以及功能的好坏,对每个计数器进行功能分析。 如果所有方面均为“良好”,则服务器状态为“健康”,否则给出“病态”状态。

这是我对最重要的计数器列表的建议 ( Here is my suggestion for list of the most important counters )

The counters table consists of category, counter name, description, and good values

计数器表由类别,计数器名称,描述和良好值组成

Range, bad value ranges

范围,错误值范围

Category Counter Name Description Good range values Bad range values
Memory/Buffer Manager Buffer cache hit ratio

The buffer cache hit ratio counter represents an indication of the percentage of data pages that exists in SQL Server’s memory and without forcing the Server to get them from the disk.

The closer this number is to 100 percent, the better.

The common threshold considered for this counter is around 90%.

A lower hit ratio value than 90% indicates clearly a memory problem and is a clear indication that memory should be extended/added to the SQL Server RAM.

>= 90% < 90%

CPU/ Processor

% user time

The % user time counter in the CPU / Processor category stands for the percentage of the processor non-idle time spent on executing the SQL user processes

The recommendation value for THE Processor: % user time is below 70%

There are some SQL experts state that 80% should be the threshold for CPU problems instead if 70 %.

This counter is also called CPU Usage % in some SQL versions

=< 70%

> 70%

Disk

Avg. Disk Sec/Read

The Avg. Disk Sec/ Read counter stands for the measure of disk latency representing the average time, in milliseconds. For each read to disk where > 20 is considered being poor, <20 is considered being good/fair, <12 is considered to be better and <8 is considered the best

=< 20MS

> 20MS

Disk

Avg. Disk Sec/Write

The Avg. Disk Sec/Write counter stands for a measure of disk latency representing the average time, in milliseconds, for each write to disk, where non-cached writes > 20 is considered being poor, <20 is considered being fair, <12 is considered better, <8 is considered the best level

This counter differs significantly from the cached writes counter where > 4 is considered poor, <4 is considered fair, <2 better, <1 is the considered the best.

For OLTP databases, the lower this number the better, especially for disks holding the Transaction log.

=< 20MS

> 20MS

Locks

Avg Wait Time (in ms)

The average wait time, in milliseconds, for each lock request that had to wait.

An average wait time longer than 500ms may indicate excessive blocking. This value should generally correlate to the ‘Lock Waits/sec’ counter

=< 500MS

> 500MS
类别 柜台名称 描述 良好的范围 范围 值错误
内存/缓冲区管理器 缓冲区高速缓存命中率

缓冲区高速缓存命中率计数器表示SQL Server内存中存在的数据页百分比的指示,而不强制Server从磁盘获取它们。

此数字越接近100%越好。

该计数器考虑的通用阈值约为90%。

低于90%的命中率值显然表明存在内存问题,并且明确表明应将内存扩展/添加到SQL Server RAM。

> = 90% <90%

CPU /处理器

用户时间百分比

“ CPU /处理器”类别中的“用户时间百分比计数器”代表执行SQL用户进程所花费的处理器非空闲时间的百分比

THE Pr​​ocessor的建议值:%用户时间低于70%

有一些SQL专家指出80%应该是CPU问题的阈值,而不是70%。

在某些SQL版本中,此计数器也称为CPU使用率%

= <70%

> 70%

磁碟

平均 磁盘秒/读取

平均 Disk Sec / Read计数器代表磁盘等待时间的度量,代表平均时间(以毫秒为单位) 。 对于每一次大于20的磁盘读为差,小于20的磁盘为好/中等,小于12的磁盘为更好,小于8的磁盘被认为是最好的

= <20毫秒

> 20毫秒

磁碟

平均 磁盘秒/写

平均 Disk Sec / Write计数器代表磁盘延迟的度量,代表对磁盘的每次写入的平均时间(以毫秒单位) ,其中非缓存写入> 20被认为是差的,<20被认为是合理的,<12被认为是更好的,<8被认为是最好的水平

该计数器与高速缓存的写计数器有显着不同,在高速缓存的写计数器中,> 4被认为是差的,<4被认为是合理的,<2是更好的,<1被认为是最好的。

对于OLTP数据库,此数字越小越好,特别是对于保存事务日志的磁盘。

= <20毫秒

> 20毫秒

锁具

平均等待时间(以毫秒为单位)

每个必须等待的锁定请求的平均等待时间(以毫秒为单位)。

平均等待时间超过500ms可能表示过多的阻塞。 此值通常应与“锁定等待/秒”计数器相关

= <500毫秒

> 500毫秒

Here is the user defined multi-statement table valued function T-SQL code:

这是用户定义的多语句表值函数T-SQL代码:


Create FUNCTION getSQLServerHealthState ()
RETURNS
@SQLServerHealthState table (counter_name  Varchar(100),counter_value decimal (7,2),verdict       varchar(10))
AS
BEGIN/* Memory cache hit ratio counter */INSERT INTO @SQLServerHealthState select counter_name , avg(cntr_value),iif (avg(cntr_value) >= 90 ,'good', 'bad')  as verdict  from sys.dm_os_performance_counters where counter_name  = 'Buffer cache hit ratio' group by  counter_name  /* CPU usage counter */INSERT INTO @SQLServerHealthState        select counter_name , avg(cntr_value), iif (avg(cntr_value) <= 70 , 'good', 'bad')  as verdict  from sys.dm_os_performance_counters where      counter_name  = 'CPU Usage %'      group by  counter_name     /* Locks counter */INSERT INTO @SQLServerHealthState  select counter_name,avg(cntr_value) , iif (avg(cntr_value) <= 500 , 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters where      counter_name  = 'Lock Wait Time (ms)'      group by  counter_name    /* Disk Read */INSERT INTO @SQLServerHealthState   select counter_name , avg(cntr_value),iif (avg(cntr_value) <= 20 , 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters where      counter_name  = 'Disk Read IO/sec'                                                                                                             group by counter_name    /* Disk write */INSERT INTO @SQLServerHealthState    select counter_name , avg(cntr_value),iif (avg(cntr_value) <= 20 , 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters where      counter_name  = 'Disk Write IO/sec'                                                                                                             group by counter_name insert into @SQLServerHealthStateselect 'SERVER STATE', NULL , (SELECT IIF (COUNT(*) = 5 ,'Healty' , 'Sick') from @SQLServerHealthState where verdict = 'good')RETURN
END
GO

Note: create and compile the function in the master database

注意 :在master数据库中创建和编译函数

代码说明: ( Explanation for the code: )

I called my multi statement, table valued function getSQLServerHealthState, it gets no parameters and outputs, as the result set a table with the selected five counters, their values and the verdict: good or bad value.

我调用了多语句,即表值函数getSQLServerHealthState ,它没有任何参数和输出,结果是设置了具有所选五个计数器,它们的值和结论的表:好值或坏值。

The functions query the sys.dm_os_performance_counters dynamic view. It assumes that there exists more than one counter with the same name corresponding to various SQL instances.

这些函数查询sys.dm_os_performance_counters动态视图。 假定存在多个计数器,这些计数器具有与各种SQL实例相对应的相同名称。

Because there can be several values for each counter, a AVG group function is used in order to get the mean value for each counter for all of the servers activity on each counter.

因为每个计数器可以有多个值,所以使用AVG组功能可以获取每个计数器上所有服务器活动的每个计数器的平均值。

An IIF function gets the verdict by operating directly on the result value of the AVG function.

通过直接对AVG函数的结果值进行操作,IIF函数可以得出结论。

For each counter, the rule from documentation is applied.

对于每个计数器,将应用文档中的规则。

At the end, a summary line is added. If all rows are set to ‘good’ then healthy status is given, else a Sick status is given

最后,添加了摘要行。 如果所有行均设置为“良好”,则给出健康状态,否则给出病态

The function was successfully tested on my server which is SQL Server 2014 express edition.

该功能已在我SQL Server 2014 Express版服务器上成功测试。

Here is an example for the function’s execution done on my server:

这是在服务器上执行该函数的示例:


Use master
Go
SELECT * from dbo.getSQLServerHealthState()

该功能的代码改进建议: ( A code improvement suggestion for the function: )

A suggested improvement for the code will be to put all the threshold values in a Dedicated table and access it with a scalar function. Then use this function inside the Multi-statement table function.

该代码的建议改进方法是将所有阈值放入专用表中,并使用标量函数进行访问。 然后在多语句表函数中使用此函数。

Thus, changing the threshold values will not force code changes inside the function Definition.

因此,更改阈值将不会在功能定义内强制更改代码。

代码改进步骤: ( Code improvement steps: )

  1. Create the threshold table in master database:

    在主数据库中创建阈值表:

    CREATE TABLE dbo.thresholds ( counter_key VARCHAR(32) ,threshold_value INT ) GO INSERT INTO dbo.thresholds ( counter_key ,threshold_value ) VALUES ( ‘Buffer cache hit ratio’ ,90 ) ,( ‘CPU Usage %’ ,70 ) ,( ‘Lock Wait Time (ms)’ ,500 ) ,( ‘Disk Read IO/sec’ ,20 ) ,( ‘Disk Write IO/sec’ ,20 ) GO

    创建表dbo.thresholds(counter_key VARCHAR(32),threshold_value INT)插入dbo.thresholds(counter_key,threshold_value)VALUES('Buffer cache hit ratio',90),('CPU Usage%',70),('锁定等待时间(ms)',500),('磁盘读IO /秒',20),('磁盘写IO /秒',20)转到

  2. The next step is to Create a scalar function called GetThresholdValue in order to access the threshold values from the table, since it is an inner use scalar function, no errors are assumed, so not error handling is coded in the function’s definition.

    下一步是创建一个名为GetThresholdValue的标量函数,以便从表中访问阈值,因为它是内部使用的标量函数,所以不会出现错误,因此该函数的定义中未编码错误处理。

     CREATE FUNCTION GetThresholdValue (@key VARCHAR(32))
    RETURNS INT
    AS
    BEGIN-- Declare the return variable DECLARE @Result INT-- T-SQL statements to compute the return value hereSELECT @Result = threshold_valueFROM dbo.thresholdsWHERE counter_key = @key-- Return the result of the functionRETURN @Result
    END
    GO
  3. getSQLServerHealthStategetSQLServerHealthState

Here is the modified and improved T-SQL code for the function:

这是对该函数的修改和改进的T-SQL代码:


alter FUNCTION [dbo].[getSQLServerHealthState] ()
RETURNS
@SQLServerHealthState table (counter_name  Varchar(100),counter_value decimal (7,2),verdict       varchar(10))
AS
BEGIN/* Memory cache hit ratio counter */INSERT INTO @SQLServerHealthState select counter_name , avg(cntr_value)  ,iif (avg(cntr_value) >= dbo.GetThresholdValue ( 'Buffer cache hit ratio'), 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters   where counter_name  = 'Buffer cache hit ratio' group by  counter_name  /* CPU usage counter */INSERT INTO @SQLServerHealthState      select counter_name ,avg(cntr_value) , iif (avg(cntr_value) <= dbo.GetThresholdValue ( 'CPU Usage %') , 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters   where      counter_name  = 'CPU Usage %'      group by  counter_name     /* Locks counter */INSERT INTO @SQLServerHealthState select counter_name , avg(cntr_value) , iif (avg(cntr_value) <= dbo.GetThresholdValue ( 'Lock Wait Time (ms)') , 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters   where      counter_name  = 'Lock Wait Time (ms)'      group by  counter_name    /* Disk Read */INSERT INTO @SQLServerHealthState  select counter_name , avg(cntr_value) , iif (avg(cntr_value) <= dbo.GetThresholdValue ( 'Disk Read IO/sec' ) , 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters    where      counter_name  = 'Disk Read IO/sec'                                                                                                             group by counter_name    /* Disk write */INSERT INTO @SQLServerHealthState   select counter_name , avg(cntr_value) , iif (avg(cntr_value) <= dbo.GetThresholdValue ( 'Disk Write IO/sec') , 'good' , 'bad')  as verdict  from sys.dm_os_performance_counters    where      counter_name  = 'Disk Write IO/sec'                                                                                                             group by counter_name insert into @SQLServerHealthState  select    'SERVER STATE', NULL , (SELECT IIF (COUNT(*) = 5 ,'Healty' , 'Sick') from @SQLServerHealthState     where verdict = 'good')RETURN
END
GO

翻译自: https://www.sqlshack.com/construct-a-special-multi-statement-table-function-for-checking-sql-servers-health/

sql多语句表值函数

sql多语句表值函数_构造一个特殊的多语句表函数来检查SQL Server的运行状况相关推荐

  1. sql判断邮箱是否合法_分享一个oracle身份证校验函数,判断你的身份证是否合法...

    概述 有个朋友说能不能用函数来实现对身份证的校验,所以这里用Oracle的函数来实现,其他数据库异曲同工.. 身份证校验函数 CREATE OR REPLACE FUNCTION Func_check ...

  2. 造成sql注入的功能点_创建一个SQL注入保护功能

    造成sql注入的功能点 .SQLCode { font-size: 13px; font-weight: bold; font-family: monospace;; white-space: pre ...

  3. SQL允许你用EXECUTE执行一个变量中定义的SQL语句,并且允许你在被执行的SQL语句中,再次嵌套入一个变量定义的语句,并且再次在其中用EXECUTE执行它...

    declare @sqlstr varchar(3000) set @sqlstr='declare @subsqlstr varchar(1000);' set @sqlstr=@sqlstr+'s ...

  4. python自定义函数判断一个数是否大于0_Python_代码练习_写一个判断是否为小数的函数...

    这两天在学习函数,练习写一个判断是否为小数的函数,看起来蛮简单的,飞速写完很是得意,然后测了一下,发现差得好多呀,这个并不像想象那样简单,我得到的教训是,想要把一个需求哪怕再小的需求考虑周全,都不是件 ...

  5. python声明匿名函数_举例讲解Python的lambda语句声明匿名函数的用法

    所谓匿名函数,即是不需要定义函数,像表达式一样使用,不需要函数名(很多时候名字让我很困扰),一些简单的函数简单化, 举个例子 我需要两个整数相加的函数,通常是这么定义的def add(x, y): r ...

  6. python函数对变量的作用遵守原则有哪四条_创建一个包含四个参数的函数

    是的,所以我在做家庭作业,我被要求做以下工作: 创建一个名为student data的函数,它接受四个参数,一个名称(一个字符串).一个年龄(一个整数).一个学生编号(一个字符串)以及他们是否在CSC ...

  7. python类的成员函数_注入一个python类成员函数

    你在这里要做的是Child2.foo用self不是a的方法调用未绑定的方法Child2. 这是非法的,Python 2将检测到并提出一个TypeError解释错误的地方:TypeError: unbo ...

  8. append函数_连载|想用Python做自动化测试?函数的参数传递机制及变量作用域

    " 这一节有点难.看不懂没关系.继续往后学,回头再来看." 10.6 函数参数传递的机制 10.6.1 值传递与引用传递 编程语言的参数传递机制通常有两种: 值传递 拷贝参数的值, ...

  9. python偏函数和高阶函数_【Python入门】8.高阶函数之 匿名函数和偏函数

    目录 高阶函数 匿名函数 lambda 偏函数 高阶函数 匿名函数 lambda lambda,即希腊字母λ.顾名思义,匿名函数没有函数名,在运用时采取lambda x : ...的方式,如lambd ...

最新文章

  1. iOS 上常用的两个功能:点击屏幕和return退出隐藏键盘和解决虚拟键盘
  2. 学习javascript 非常好的博客
  3. 《卓有成效的程序员》----读书笔记二
  4. 在阿里干了五年,面试个小公司挂了…
  5. mysql的多master调度_innodb中master线程的调度的算法改进(mysql 5.6.26)
  6. C++ 高级篇(二)—— 名空间 (Namespaces)
  7. 为什么索引不支持模糊查询_百度站长平台查询的关键词排名,为什么与实际不符合?...
  8. 奇安信代码安全实验室招贤纳士
  9. moonlight不显示鼠标指针
  10. JAVA中的继承和覆盖
  11. SD卡格式化咋办?数据恢复看这里!
  12. 软件需求跟踪矩阵例子
  13. javascript案例10——下拉菜单
  14. 使用xpath批量爬取堆糖图片
  15. 手机中的小金库被盗?手机支付安全如何保障
  16. 戴尔高密度服务器性能指标,PowerEdge R630:1U机身下的2U性能
  17. CAD图如何导入Visio
  18. 面向大数据的分布式调度
  19. Item Categories
  20. JSON 的文档数据库 RedisJson 介绍

热门文章

  1. 解决 ‘Could not fetch URL https://pypi.python.org’的问题
  2. python开发总结
  3. xxx is not in the sudoers file. This incident will be reported
  4. HIVE 1.1.0 启动时报错: Unsupported major.minor version 51.0
  5. javascript的内置对象
  6. [Android]Notification汇总
  7. 实现基于AD的MOSS的FORM认证方式
  8. ★LeetCode(448)——找到所有数组中消失的数字(JavaScript)
  9. The following tasks did not complete: first Did you forget to signal async completion?
  10. 数据库原理—常用的DBS产品简介(六)