search
HomeDatabaseMysql Tutorial第十七章配置SQLServer(3)配置“对即时负载的优化”

前言: 在第一次执行查询或者存储过程时,会创建执行计划并存储在SQLServer的过程缓存内存中。在很多时候,我们会执行一些简单的程序,仅仅执行一次,而为这些查询创建存储过程是非常浪费内存资源的。由于内存不足,可能会导致你的缓存溢出,从而影响性能。

前言:

        在第一次执行查询或者存储过程时,会创建执行计划并存储在SQLServer的过程缓存内存中。在很多时候,我们会执行一些简单的程序,仅仅执行一次,而为这些查询创建存储过程是非常浪费内存资源的。由于内存不足,可能会导致你的缓存溢出,从而影响性能。在2005之前,这是一个大问题,为了纠正这个问题。微软在SQLServer 2008中引入了对即时查询负载的优化功能。这个功能在2012也依旧可用。是基于实例级别的。

        很多开发人员直接在生产环境运行和测试查询,如果没有得到期望的结果,会更改查询然后再次执行,这会对过程缓存造成很大压力。所以尽量不要这样做。

 

准备工作:

在开始之前,在测试服务器清空缓存,但是切记不要在生产环境这样做:

1、 先看看有多少数据保存在缓存中:


SELECT  CP.usecounts AS CountOfQueryExecution ,
        CP.cacheobjtype AS CacheObjectType ,
        CP.objtype AS ObjectType ,
        ST.text AS QueryText
FROM    sys.dm_exec_cached_plans AS CP
        CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS ST
WHERE   CP.usecounts > 0
GO



结果如下:


第十七章配置SQLServer(3)配置“对即时负载的优化”

2、 清空缓存和缓冲池:

DBCC FREEPROCCACHE 
GO


3、 如果想检查是否清空成功,可以再次执行步骤1中的语句: 

 第十七章配置SQLServer(3)配置“对即时负载的优化”

步骤:

1、 执行下面语句:


USE AdventureWorks
GO
SELECT  *
FROM    Sales.SalesOrderDetail
WHERE   SalesOrderDetailID = 43659
GO


2、 检查在运行了上面语句后是否有计划缓存,再次执行之前查询计划缓存的语句: 

SELECT  CP.usecounts AS CountOfQueryExecution ,
        CP.cacheobjtype AS CacheObjectType ,
        CP.objtype AS ObjectType ,
        ST.text AS QueryText
FROM    sys.dm_exec_cached_plans AS CP
        CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS ST
WHERE   CP.usecounts > 0
GO



3、 下面是结果,当然,也可以在where条件中用like来减少查找的数据量:也可以使用ctrl+alt+a来开启活动监视器来查找运行时间长的查询。

第十七章配置SQLServer(3)配置“对即时负载的优化”

4、 现在来把Optimize for Ad hoc Workloads设为1:

 EXEC sp_configure 'optimize for ad hoc workloads', 1
RECONFIGURE
GO



5、 然后再次清空缓存: 

DBCC FREEPROCCACHE 
GO


6、 再次执行语句:


USE AdventureWorks
GO
SELECT  *
FROM    Sales.SalesOrderDetail
WHERE   SalesOrderDetailID = 43659
GO


7、 可以执行下面的语句检查是否有新的缓存进入: 

SELECT  CP.usecounts AS CountOfQueryExecution ,
        CP.cacheobjtype AS CacheObjectType ,
        CP.objtype AS ObjectType ,
        ST.text AS QueryText
FROM    sys.dm_exec_cached_plans AS CP
        CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS ST
WHERE   CP.usecounts > 0
        AND ST.text LIKE '%SELECT  *  FROM    Sales.SalesOrderDetail  WHERE   SalesOrderDetailID = 43659  %'
        AND CP.cacheobjtype = 'Compiled Plan'
GO



8、 你会发现里面没有数据,现在再次执行下面语句: 


USE AdventureWorks
GO
SELECT  *
FROM    Sales.SalesOrderDetail
WHERE   SalesOrderDetailID = 43659
GO


9、 使用以下查询检查: 


SELECT  CP.usecounts AS CountOfQueryExecution ,
        CP.cacheobjtype AS CacheObjectType ,
        CP.objtype AS ObjectType ,
        ST.text AS QueryText
FROM    sys.dm_exec_cached_plans AS CP
        CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS ST
WHERE   CP.usecounts > 0
        AND ST.text LIKE '%SELECT  *  FROM    Sales.SalesOrderDetail  WHERE   SalesOrderDetailID = 43659  %'
        AND CP.cacheobjtype = 'Compiled Plan'
GO



10、这次就出现了下面的截图: 

 第十七章配置SQLServer(3)配置“对即时负载的优化”

 

分析:

        当新查询执行时,query_hash值会在内存中生成,而不是整个执行计划,当相同的查询第二次执行的时候,SQLServer会查找是否已经存在这个query_hash,如果不存在,执行计划将保存在缓存中。这样就使得仅执行一次的查询将不会保存执行计划到缓存中。所以强烈建议打开这个配置。这个配置不造成任何负面影响,但是可以节省计划缓存的空间。

        一般情况下,当你执行查询,将会产生执行计划并保存在过程缓存中,所以当你执行步骤1的查询是,会看到服务器有很多计划缓存,但是当执行第六步后的查询是,就发现没有。对于即席查询,如果只执行一次,何必需要缓存呢?

        有些系统的计划缓存达到GB以上,开启后可能减少一半空间。另外,如果你好奇即席查询占用了多少空间,可以使用下面的语句:

SELECT  SUM(size_in_bytes) AS TotalByteConsumedByAdHoc
FROM    sys.dm_exec_cached_plans
WHERE   objtype = 'Adhoc'
        AND usecounts = 1


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools