博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
sql多语句表值函数_构造一个特殊的多语句表函数来检查SQL Server的运行状况
阅读量:2513 次
发布时间:2019-05-11

本文共 13065 字,大约阅读时间需要 43 分钟。

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)				)ASBEGIN     /* 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 @SQLServerHealthState    select 	  'SERVER STATE', NULL , 	  (SELECT IIF (COUNT(*) = 5 ,'Healty' , 'Sick') 	   from @SQLServerHealthState 	   where verdict = 'good')	     RETURNENDGO 

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 masterGoSELECT * 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 INTASBEGIN	-- Declare the return variable 	DECLARE @Result INT 	-- T-SQL statements to compute the return value here	SELECT @Result = threshold_value	FROM dbo.thresholds	WHERE counter_key = @key 	-- Return the result of the function	RETURN @ResultENDGO 
  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))ASBEGIN              /* 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')	 	RETURNENDGO 

翻译自:

sql多语句表值函数

转载地址:http://igiwd.baihongyu.com/

你可能感兴趣的文章
转自 zera php中extends和implements的区别
查看>>
Array.of使用实例
查看>>
【Luogu】P2498拯救小云公主(spfa)
查看>>
如何获取网站icon
查看>>
几种排序写法
查看>>
java 多线程的应用场景
查看>>
dell support
查看>>
转:Maven项目编译后classes文件中没有dao的xml文件以及没有resources中的配置文件的问题解决...
查看>>
MTK android 设置里 "关于手机" 信息参数修改
查看>>
单变量微积分笔记6——线性近似和二阶近似
查看>>
补几天前的读书笔记
查看>>
HDU 1829/POJ 2492 A Bug's Life
查看>>
CKplayer:视频推荐和分享插件设置
查看>>
CentOS系统将UTC时间修改为CST时间
查看>>
redis常见面试题
查看>>
导航控制器的出栈
查看>>
玩转CSS3,嗨翻WEB前端,CSS3伪类元素详解/深入浅出[原创][5+3时代]
查看>>
iOS 9音频应用播放音频之播放控制暂停停止前进后退的设置
查看>>
Delphi消息小记
查看>>
HNOI2016
查看>>