About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Monday, January 6, 2014

Plan Caching IV - Simple Parameterization in Adhoc Query Processing


Read Previous Post:

Some time SQL Server consider some constant of Query as a Parameter, and when this happens, any query subsequently executed after that having a kind of similar template will use the same plan. We will check this by taking an example. Will try to execute sys.dm_exec_cached_plans to know the exact happening.

Now let’s set the 'optimize for ad hoc workloads' to 0

sp_CONFIGURE 'optimize for ad hoc workloads',0
RECONFIGURE
GO
Configuration option 'optimize for ad hoc workloads' changed from 0 to 0. Run the RECONFIGURE statement to install.

We need to free the Procedure cache and Buffer, so that we will get only our plan cached in the memory when we execute our set of query.

dbcc FREEPROCCACHE
DBCC DROPCLEANBUFFERS
Go
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Now since our cache memory is free, let’s fire a SQL query and check the cache using DMV sys.dm_exec_cached_plans.

select * from emp where emp_id = 1
go
select * from emp where emp_id = 2
go
select * from emp where emp_id = 3
go

select usecounts, cacheobjtype, objtype, [text]
from sys.dm_exec_cached_plans
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
where usecounts > 0
AND
[text] not like '%dm_exec_cached_plans%' and [text] not like  '%dm_exec_sql_text%'
order by usecounts desc
go

usecounts cacheobjtype  objtype  text
--------  ------------- -------- --------------------------------------------
3         Compiled Plan Prepared (@1 tinyint)SELECT * FROM emp WHERE emp_id=@1
1         Compiled Plan Adhoc    select * from emp where emp_id = 3
1         Compiled Plan Adhoc    select * from emp where emp_id = 2
1         Compiled Plan Adhoc    select * from emp where emp_id = 1

Here we can see that the plan is first compiled and cached in memory taking constant as parameter and when next time a query of similar kind came for execution, this plan which is cached in memory gets referenced by the executer.

And the rest three compiled plan is just stored to as an act of finding parameterized version of the query, if exact same query with same constant come for execution.

Code is a kind of color in programmers being, to aid & strikes the pond of contentment… 


Post Reference: Vikram Aristocratic Elfin Share

No comments:

Post a Comment