How to observe SQL Server generation and reuse execution plans

Source: Internet
Author: User

An SQL statement for data query must be evaluated by SQL Server and generate the corresponding execution plan. Finally, the actual query operation is generated based on the Execution Plan and the result set is returned to the client, evaluating and generating an execution plan is a few CPU-consuming tasks. Therefore, SQL Server does not re-evaluate and generate an execution plan every time, in addition, for many SQL statements with different parameter values, their execution plans should be the same, for example, for the following two SQL statements:

DECLARE @OrderID INT
SET @OrderID = 123
EXEC sp_executesql N'SELECT TOP 1 * FROM dbo.tblOrders WHERE OrderID = @OrderID', N'@OrderID INT', @OrderID
GO

DECLARE @OrderID INT
SET @OrderID = 456
EXEC sp_executesql N'SELECT TOP 1 * FROM dbo.tblOrders WHERE OrderID = @OrderID', N'@OrderID INT', @OrderID
GO

Therefore, to optimize the performance of the database system, the general database system caches the execution plan and designs a mechanism to reuse the cached execution plan.

To test and observe how SQL Server generates and reuse execution plans, you can use the following method:

First, use the following statement to clear the execution plan cache:

  DBCC FREEPROCCACHE

Use the following statement to view the execution plan after clearing:

  select * from sys.syscacheobjects

Run the following statement to generate an execution plan for SQL Server:

DECLARE @OrderID INT
SET @OrderID = 123
EXEC sp_executesql N'SELECT TOP 1 * FROM dbo.tblOrders WHERE OrderID = @OrderID', N'@OrderID INT', @OrderID
GO

DECLARE @OrderID INT
SET @OrderID = 456
EXEC sp_executesql N'SELECT TOP 1 * FROM dbo.tblOrders WHERE OrderID = @OrderID', N'@OrderID INT', @OrderID
GO

Finally, use the following statement to observe the execution plan generation and reuse mechanism.

select * from sys.syscacheobjects where sql not like '%syscacheobjects%' and sql like '%tblOrders%'

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.