SQL Server parameterized query Experience Sharing

Source: Internet
Author: User

What is parameterized query?
A simple way to understand parameterized queries is to think of it as just a T-SQL query that accepts parameters that control what the query returns. By using different parameters, a parameterized query returns different results. To obtain a parameterized query, you need to write your Code Or it must meet a specific set of standards.

There are two different ways to create a parameterized query. The first method is to allow the query optimizer to automatically parameterize your query. Another way is to program a parameterized query by writing your T-SQL code in a specific way and passing it to the sp_executesql system stored procedure. This articleArticleThis method is described later in.

The key to parameterized query is that the query optimizer will create a reusable cache plan. By automatically or programmatically using parameterized queries, SQL Server can optimize processing like T-SQL statements. This optimization eliminates the need to create a cache plan for each execution of these similar T-SQL statements using noble resources. In addition, by creating a reusable plan, SQL Server also reduces the memory usage required for similar execution plans stored in the cache during the process.

Now let's take a look at the different ways in which SQL Server creates parameterized queries.

How is a parameterized query automatically created?

The person who writes the query optimizer code at Microsoft is doing their best to optimize the way SQL server handles your T-SQL commands. I think this is the source of the query optimizer name. One of these ways to minimize resources and maximize query optimizer execution performance is to view a T-SQL statement and determine if they can be parameterized. To understand how this works, let's look at the following T-SQL statement:

Select *
From adventureworks. Sales. salesorderheader
Where salorderid = 56000;
Go

Here, you can see that this command has two features. First, it is simple, and second, it contains a specified value for the salesorderid value in the where predicate. The query optimizer can identify that this query is relatively simple and that salesorderid has a parameter ("56000 "). Therefore, the query optimizer can automatically parameterize this query.

If you use the following SELECT statement to view a clean buffer pool that only contains the cache plan for the preceding statement, then you will see the query optimizer override the T-SQL Query into a parameterized T-SQL statement:

Select stats.exe cution_count as CNT,
P. size_in_bytes as [size],
[SQL]. [text] as [plan_text]
From SYS. dm_exec_cached_plans P
Outer apply SYS. dm_exec_ SQL _text (P. plan_handle) SQL
Join SYS. dm_exec_query_stats stats
On stats. plan_handle = P. plan_handle;
Go

When I run this command on an SQL Server 2008 instance, I get the following output (note that the output is reformatted to make it easier to read ):

CNT size plan_text

------------------------------------------------------------------------

1 49152 (@ 1 INT) Select * from [adventureworks]. [sales]. [salesorderheader]

Where [salesorderid] = @ 1

If you look at the plan_text field in the output above, you will see that it is not like the original T-SQL text. As described above, the query optimizer rewrites this query into a parameterized T-SQL statement. Here, you can see that it now has a variable (@ 1) of the data type (INT), which is defined in the previous SELECT statement. In addition, at the end of plan_text, the value of "56000" is replaced with the variable @ 1. Since this T-SQL statement is overwritten and stored as a cache plan, if a future T-SQL command is roughly the same as it, only the salesorderid field is assigned a different value, it can be used for reuse. Let's look at it in action.

If I run the following command on my machine:

DBCC freeproccache;
go
select *
from adventureworks. sales. salesorderheader
where salesorderid = 56000;
go
select *
from adventureworks. sales. salesorderheader
where salesorderid = 56001;
go
select stats.exe cution_count as CNT,
P. size_in_bytes as [size],
[SQL]. [text] as [plan_text]
from sys. dm_exec_cached_plans P
outer apply sys. dm_exec_ SQL _text (P. plan_handle) SQL
join sys. dm_exec_query_stats stats
on stats. plan_handle = P. plan_handle;
go
I got the following output from the last SELECT statement (note that the output is reformatted to make it easier to read ):
CNT size plan_text
--- -------- --------------------------------------------------------------
2 49152 (@ 1 INT) Select * From adventureworks]. [sales]. [salesorderheader]
where [salesorderid] = @ 1

Here, I first release the process cache, then I run two different but similar non-parametric queries to see if the query optimizer creates two different cache plans or creates a cache plan for these two queries. Here, you can see that the query optimizer is actually very clever, it parameterized the first query and cached the plan. Then, when the second similar query with a different salesorderid value is sent to SQL Server, the optimizer can identify that a plan has been cached and then reuse it to process the second query. You can say this because the "CNT" field now indicates that this plan was used twice.

Database Configuration option parameterization can affect how T-SQL statements are automatically parameterized. There are two different settings for this option, simple and forced. When parameterization settings are set to simple, only simple T-SQL statements are parameterized. To introduce this, see the following command:

Select sum (linetotal) as linetotal
From adventureworks. Sales. salesorderheader H
Join adventureworks. Sales. salesorderdetail D on D. salesorderid = H. salesorderid
Where H. salesorderid = 56000

This query is similar to my previous example, except that an additional join standard is added here. When the parameterization option of database adventureworks is set to simple, this query will not be automatically parameterized. The simple parameterization setting tells the query optimizer to only parameterize simple queries. However, when parameterization is set to forced, the query is automatically parameterized.

When you set the database option to force parameterization, the query optimizer tries to parameterize all the queries, not just simple queries. You may think this is good. However, in some cases, when parameterization is set to forced in the database, the query optimizer selects a query plan that is not ideal. When the database sets parameter to forced, it changes the literal constant in the query. This may result in an invalid plan because the index and index view are not selected to participate in the execution plan when a calculated field is involved in the query. The forced parameterization option may be a good solution to improve the performance of databases with a large number of similar and slightly different passed parameters. An online sales applicationProgramIts customers perform a large number of similar searches for your product, with different product values. This may be a good application type that can benefit from forced parameterization.

Not all query clauses are parameterized. For example, the top, tablesample, having, group by, order by, output... into, or for XML clauses queried are not parameterized.

Use sp_execute_ SQL to parameterize your T-SQL

You do not need to rely on the database parameterization option to parameterize a query by the query optimizer. You can parameterize your own queries. You're done by re-writing your T-SQL statement and executing the override statement using the "sp_executesql" system stored procedure. As you can see, the SELECT statement that includes a "join" clause is not automatically parameterized when the database's parameterization is set to simple. Let me re-compile this query so that the query optimizer will create a reusable parameterized query execution plan.

For illustration, Let's see two similar T-SQL statements that are not automatically parameterized and create two different cache execution plans. Then I will re-compile these two queries so that they all use the same cache parameterized execution plan.

Let's take a look at this Code:

DBCC freeproccache
Go
Select sum (linetotal) as linetotal
From adventureworks. Sales. salesorderheader H
Join adventureworks. Sales. salesorderdetail D on D. salesorderid = H. salesorderid
Where H. salesorderid = 56000
Go
Select sum (linetotal) as linetotal
From adventureworks. Sales. salesorderheader H
Join adventureworks. Sales. salesorderdetail D on D. salesorderid = H. salesorderid
Where H. salesorderid = 56001
Go
Select stats.exe cution_count as CNT,
P. size_in_bytes as [size],
Left ([SQL], [text], 200) as [plan_text]
From SYS. dm_exec_cached_plans P
Outer apply SYS. dm_exec_ SQL _text (P. plan_handle) SQL
Join SYS. dm_exec_query_stats stats on stats. plan_handle = P. plan_handle;
Go

Here I release the process cache and then run the two non-simple T-SQL statements that contain a join. Then I will check the cache plan. This is the output of the SELECT statement using DMV (note that the output is reformatted to make it easier to read ):

CNT size plan_text
--- ----------- success
1 49152 select sum (linetotal) as linetotal
from adventureworks. sales. salesorderheader H
join adventureworks. sales. salesorderdetail d
on D. salesorderid = H. salesorderid
where H. salesorderid = 56001
1 49152 select sum (linetotal) as linetotal
from adventureworks. sales. salesorderheader H
join adventureworks. sales. salesorderdetail d
on D. salesorderid = H. salesorderid
where H. salesorderid = 56000

as you can see from this output, the two select statements are not parameterized by the query optimizer. The optimizer creates two different cache execution plans, each of which is executed only once. We can use the sp_executesql system stored procedures to help the optimizer create a parameterized execution plan for these two different select statements.
the following code is rewritten to use the sp_executesql system stored procedure:

DBCC freeproccache;
go
exec sp_executesql n' select sum (linetotal) as linetotal
from adventureworks. sales. salesorderheader H
join adventureworks. sales. salesorderdetail D on D. salesorderid = H. salesorderid
where H. salesorderid = @ salesorderid ', n' @ salesorderid int', @ salesorderid = 56000;
go
exec sp_executesql n' select sum (linetotal) as linetotal
from adventureworks. sales. salesorderheader H
join adventureworks. sales. salesorderdetail D on D. salesorderid = H. salesorderid
where H. salesorderid = @ salesorderid ', n' @ salesorderid int', @ salesorderid = 56001;
go
select stats.exe cution_count as exec_count,
P. size_in_bytes as [size],
[SQL]. [text] as [plan_text]
from sys. dm_exec_cached_plans P
outer apply sys. dm_exec_ SQL _text (P. plan_handle) SQL
join sys. dm_exec_query_stats stats on stats. plan_handle = P. plan_handle;
go

As you can see, I re-compiled the two select statements so that they can be executed by using the "Exec sp_executesql" statement. For each of these exec statements, I pass three different parameters. The first parameter is a basic SELECT statement, but I replace the value of salesorderid with a variable (@ salesorderid. In the second parameter, I have determined the Data Type of @ salesorderid. In this example, it is an integer. Then, in the last parameter, I passed the value of salesorderid. This parameter controls the results generated by my select based on the salesorderid value. The first two parameters in each execution of sp_executesql are the same. However, the third parameter is different because each parameter has a different salesorderid value.

Now when I run the above code, I get the following output from the DMV SELECT statement (note that the output is reformatted to make it easier to read ):

CNT size plan_text
--- ----------- Begin -------------------------------------------------------------------------------------------------------
2 49152 (@ salesorderid INT) Select sum (linetotal) as linetotal
From adventureworks. Sales. salesorderheader H
Join adventureworks. Sales. salesorderdetail D on D. salesorderid = H. salesorderid
Where H. salesorderid = @ salesorderid

From this output, you can see that I have a parameterized cache plan that is executed twice and each exec statement is executed once.

Use parameterized query to save resources and optimize performance

before a statement can be executed, each T-SQL statement needs to be evaluated and an execution plan needs to be created. Creating an execution plan consumes valuable CPU resources. When an execution plan is created, it uses the memory space to store it in the process cache. One way to reduce CPU and memory usage is to use parameterized queries. Although the database can be set to force parameterization for all queries, this is not always the best choice. By understanding which of your T-SQL statements can be parameterized and then using sp_executesql stored procedures, you can help SQL Server save resources and optimize the performance of your queries.

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.