Plan_handle in sys.dm_exec_requests and sys.dm_exec_cached_plans

We are a SQL 2008 R2 Ent shop and recently I am troubling a performance issue which one SQL server is performing much faster than another SQL server for the exact same query.  Each SQL server produces quite a different execution plan than
the other.  This is another topic on its own which I won't touch here.   While using DMV to trouble shoot, I come across a plan handle question regarding these two DMV's. I use sys.dm_exec_requests to check what are currently running
on a SQL server and sys.dm_exec_cached_plans to check what plans are being cached.    When I run the 'long running' query and check the plan handle in dm_exec_requests and dm_exec_cached_plans, the plan handle number in dm_exec_requests doesn't
show up in sys.dm_exec_cached_plans.  In fact, the plan handle in dm_exec_cached_plans is different for the same 'long running' query.   Can someone explain why? 
It is important for me to know because when I am trouble shooting a frequently long running query, I would first try to kill its execution plan because it may become inefficient due to a parameter sniffing issue.   I normally
use the plan handle from sys.dm_exec_requests to get a 'cached' plan handle number and use DBCC FREEPROCCACHE (xxxxxxxxxxx) to kill it.  However, I would expect the same plan handle number from sys.dm_exec_cached_plans for that query but
it is not.  So this leads me to think that I may not be removing the plan I really want.
Besides answering my 'why they are different' question, I also like to know if my way of removing a cached plan is correct or not.  Please advice as well.
Thanks in advance,
OD
Ocean Deep

Erland,
Thanks for the reply.  I think I find the answer to my question.  The correct fact is that dm_exec_requests, dm_exec_cached_plans and even your suggested dm_exec_query_stats all find the same plan handler If I search by the plan hander number.  
If I search by the query content (st.text) , it either doesn't return any record or return records with a different plan handler number.   Let me show you what I use and may be you can correct it. 
SELECT plan_handle, st.text, cacheobjtype, objtype
FROM sys.dm_exec_cached_plans
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st
WHERE st.text LIKE N'  select lastName, FirstName %'
If I search the actual plan handler number, it would find that cached plan.
SELECT plan_handle, st.text, cacheobjtype, objtype
FROM sys.dm_exec_cached_plans
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st
where plan_handle =0x06001B00693E700240418F25030000000000000000000000
Couple points about the query using the text name for searching.  First the query was copied from one of the SQL expert blog so I assume it is working.   Secondly, the actual query text I use is straight out from a query result using
the following query so I am not guessing what the actual query format it may be.
select r.session_id, r.status,
r.start_time, r.command, s.text, r.plan_handle
from sys.dm_exec_requests r
cross apply sys.dm_exec_sql_text(r.sql_handle) s
Let me know if there is a proper way to search for a cached plan by the query content if there is one.  This is important because sometimes I may not have a plan handle number to work with and yet I need to kill a cached plan for a particular sql query
so the only thing I have is the query itself.
By the way, my long running query is not a stored procedure.  It is a query sending from a web application.
Thanks in advance,
OD
Ocean Deep

Similar Messages

  • SQL 2008 R2 standard reports - question about server dashboard and what it refers to as "adhoc" queries

    So I have started looking at some of the standard reports available with SSMS and in particular, the "server dashboard".   One thing that caught my attention were the charts that referred to "adhoc" queries.  I wondered how
    those were being defined, and as I expected, they are most likely those statements not in a stored procedure.  This was answered in
    this thread.  
    On a particular server Im interested in, this % value is well over 50% and the primary applications that interact with the databases on this system are Microsoft based products such as Dynamics and another commercial application which I know uses hundreds
    of stored procedures.  Now, Im sure there are some sql statements being used, possibly "dynamic" type sql, by these applications, but would the metrics really be skewed this far?
    What these charts tell me, with the "adhoc" statement types pushing CPU and Disk I/O %  this far, is that there is a BUNCH of these statements being run against the various databases.  The disk I/O might be a bit off since I only recently
    added dozens of missing indexes, but my question is this:
    With the "adhoc" type statements taking up this much of the CPU and Disk resources, can we say that there are likely a lot of these going on ?  I suppose one way to find out is to launch profiler and listen in while there is moderate
    to heavy user activity.
    Thoughts?

    Hello,
    Adhoc queries are DML statements with not parameterization. Sometimes users use this statements, and sometimes these statements come from applications.
    Use Query #2 on the following link to identify those adhoc queries:
    http://mssqlfun.com/2013/04/08/dmv-5-queries-runing-are-adhoc-or-proc-single-or-multi-use-sys-dm_exec_cached_plans/
    Identify if those adhoc queries belong to specific users or applications.
    One of the options you have to deal with is is the following configuration option:
    sp_CONFIGURE 'show advanced options',1
    RECONFIGURE
    GO
    sp_CONFIGURE ‘optimize for ad hoc workloads’,1
    RECONFIGURE
    GO
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • POSTING TIPS - Code, Images, Hyperlinks, Details

    When you're posting a question - please search the forum first!  If that fails, and you wish to include T-SQL, C#, or VB code in your post, see below.  If you want to show us what you see on your screen (pictures are worth a thousand words), see
    below! Check that a URL does not stay black/gray indicating an inactive hyperlink. All URL references should be blue and clickable.
    Moderators, please add any other tips you may have.
    Including T-SQL, C#, VB.Net Source Code
    (Thanks to Phil Brammer & Kalman Toth for this tip)
    When you are composing a post and you wish to paste code, please don't directly paste it into the post, instead paste it into the code block editor.  It will preserve formatting for you, which makes it easier for us to read it and help you with your issue.
    Examples follow...
    Not using the code block editor:
    select
    text, *
    from sys.dm_exec_cached_plans
    cross apply sys.dm_exec_sql_text(plan_handle)
    Using the code block editor (and with the same copy-n-paste buffer):
    select
    text, *
    from sys.dm_exec_cached_plans
    cross apply sys.dm_exec_sql_text(plan_handle)
    Including Images
    Using the Editor:
    (Thanks to Kalman Toth for these instructions)
    Use the Forum Editor method to Insert Image:
    1. Save the image to disk or copy the image URL
    2. Use the Insert Image (right most) icon to upload the image
    Make sure the URL hyperlink is active:
    The forum post editor automatically hyperlinks a typed URL in IE. But not all browsers do it.
    Use the chain link icon to hyperlink an inactive URL, title or reference.
    Using HTML:
    (Thanks to Todd McDermid & Ed Price for this tip)
    Copy your screen to the clipboard (ALT-PRTSCN) (alternatively, some image editors can do screen captures)
    Paste it in your favourite image editor
    Upload it to a free image hosting site like Flickr,
    ImageShack, ...
    Create your post, then press the "HTML" button on the post toolbar.  This will open another browser window with HTML in it.
    Find the spot where you want the image, and add a standard IMG element, pasting in the URL to your image, like this:
    < img src="http://your.url.here/your_image_filename_here">
    Press the Update button.
    The Volunteer Moderators and Answerers who support the Microsoft MSDN SQL Server Forums have created a Wiki to present Solutions to Common T-SQL Problems.
    (Thanks to Arnie Rowland  for this tip)
    Check here to see if there is a suggestion that can guide you to a solution for your problem.
    http://code.msdn.microsoft.com/SQLExamples
    If you find that the Wiki provided you with useful information, please let us know by posting a synopsis of your problem and a comment about your successful use of that information.
     “Top Solution Content” blog 
    (Thanks to Elvis Long  for this tip)
    As part of our efforts to keep our communities informed about the most relevant content that address the top questions that we are getting in out forums and other support channels we want to introduce the new “Top Solution Content” blog (http://blogs.technet.com/b/topsupportsolutions).
    In this blog you will find up-to-date and valuable information about Microsoft top support solutions for several of our popular products in the Server and Tools portfolio. You can use the tags (http://blogs.technet.com/b/topsupportsolutions/archive/tags)
    to easily locate the product of your preference or visit the home page to see what’s going on for the different Microsoft Enterprise and developer products. As a blog you can also subscribe to post and comments using the RSS feeds.
    We hope this will reduce time and effort when you are looking for relevant content. Enjoy it!
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

    the SWC thing may be exactly what I need.
    I read that link you gave me and I will definately do a little more research on SWC, even if it's not completely clear how to use them at this particular moment.
    let's say I have an image called MyImage.png which I have setup to export for actionscript on frame 1 and the class is called "MyImage"
    Assume I have the same thing setup in my library for a sound file called "MySound"
    Now, without doing any reading first, I would assume that I would create a new fla file, put those 2 assets in said fla's library and then compile that fla into an swc? And then access thoughs assets in my main project by importing the swc into it? or it is more simple than that?
    Cheers
    Dave

  • POSTING TIPS - Code, Diagrams, Hyperlinks, Details

    When you're posting a question - please search the forum first!  If that fails, and you wish to include T-SQL, C#, or VB code in your post, see below.  If you want to show us a database diagram you see on your screen (pictures are worth a
    thousand words), see below! Check that a URL does not stay black/gray indicating an inactive hyperlink. All URL references should be blue and clickable.  Moderators, please add any other tips you may have.
    Including T-SQL, C#, VB.Net Source Code
    (Thanks to Phil Brammer & Kalman Toth for this tip)
    When you are composing a post and you wish to paste code, please don't directly paste it into the post, instead paste it into the code block editor.  It will preserve formatting for you, which makes it easier for us to read it and help you with your issue.
    Examples follow...
    Not using the code block editor:
    select
    text, *
    from sys.dm_exec_cached_plans
    cross apply sys.dm_exec_sql_text(plan_handle)
    Using the code block editor (and with the same copy-n-paste buffer):
    select
    text, *
    from sys.dm_exec_cached_plans
    cross apply sys.dm_exec_sql_text(plan_handle)
    Including Images
    Using the Editor:
    (Thanks to Kalman Toth for these instructions)
    Use the Forum Editor method to Insert Image:
    1. Save the image to disk or copy the image URL
    2. Use the Insert Image (right most) icon to upload the image
    Make sure the URL hyperlink is active:
    The forum post editor automatically hyperlinks a typed URL in IE. But not all browsers do it.
    Use the chain link icon to hyperlink an inactive URL, title or reference.
    Using HTML:
    (Thanks to Todd McDermid & Ed Price for this tip)
    Copy your screen to the clipboard (ALT-PRTSCN) (alternatively, some image editors can do screen captures)
    Paste it in your favourite image editor
    Upload it to a free image hosting site like Flickr,
    ImageShack, ...
    Create your post, then press the "HTML" button on the post toolbar.  This will open another browser window with HTML in it.
    Find the spot where you want the image, and add a standard IMG element, pasting in the URL to your image, like this:
    < img src="http://your.url.here/your_image_filename_here">
    Press the Update button.
    The Volunteer Moderators and Answerers who support the Microsoft MSDN SQL Server Forums have created a Wiki to present Solutions to Common T-SQL Problems.
    (Thanks to Arnie Rowland  for this tip)
    Check here to see if there is a suggestion that can guide you to a solution for your problem.
    http://code.msdn.microsoft.com/SQLExamples
    If you find that the Wiki provided you with useful information, please let us know by posting a synopsis of your problem and a comment about your successful use of that information.
     “Top Solution Content” blog 
    (Thanks to Elvis Long  for this tip)
    As part of our efforts to keep our communities informed about the most relevant content that address the top questions that we are getting in out forums and other support channels we want to introduce the new “Top Solution Content” blog (http://blogs.technet.com/b/topsupportsolutions).
    In this blog you will find up-to-date and valuable information about Microsoft top support solutions for several of our popular products in the Server and Tools portfolio. You can use the tags (http://blogs.technet.com/b/topsupportsolutions/archive/tags)
    to easily locate the product of your preference or visit the home page to see what’s going on for the different Microsoft Enterprise and developer products. As a blog you can also subscribe to post and comments using the RSS feeds.
    We hope this will reduce time and effort when you are looking for relevant content. Enjoy it!
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

    In CSS, there are five states for links
    a:link
    a:visited
    a:hover
    a:active
    a:focus
    a:link (=unvisited, or never clicked)
    a:visited (=clicked at least once)
    a:visited is purple in most browsers by default.
    Thus, you need to define a:visited in your CSS and it should come after a:link (otherwise you'll never see it)
    One solution would be:
    a:link, a:visited {
              color: #00F;
    but bear in mind that visitors find it handy if a:visited is a different color to a:link so they know which links they've already clicked on.
    a:link {
              color: #00F;
    a:visIted {
              color: #SOME OTHER COLOR TO A:LINK;
    a:hover {
              color: #F00;

  • SQL Injection -- DBA role..

    Hi all,
    I'm working as a SQL Server DBA,Now a days we are facing issue with attacks(SQL Injection),most of attacks are taken care by Firewalls but still some attacks hitting Database.
    As a DBA  How to check whether database got effected
    Please help me by providing hints and tips to analysis SQL injection.
    Thanks in advance

    There is no easy ways to detect sql injection. You should analyze activity against databases and work with developers to address it.
    Basically, you can capture sql_completed/rpc_completed events in XEvent or SQL Trace and review them. Anything, which is not parameterized, could be the subject of injection attach (it depends on Client Code and implementation). 
    As the side note, script below provides you the list of the databases together with number of cached execution plans that were used just once. SQL Injection targets non-parameterized queries. So the databases with large number of single-used plans are more
    likely to be affected. In any case, do not rely on output much - large number of single-used plans could be just the sign of bad design rather than being affected. As I said, you need to review client app code just to be sure.
    select
    epa.value as [DB ID],
    db_name(convert(int,epa.value)) as [DB Name],
    count(*) as [Single Use Plans]
    from
    sys.dm_exec_cached_plans p
    cross apply sys.dm_exec_plan_attributes(plan_handle) AS epa
    where
    p.usecounts = 1 and
    p.objtype in ('Adhoc','Prepared') and
    epa.attribute = 'dbid'
    group by
    epa.value
    option (recompile)
    Thank you!
    Dmitri V. Korotkevitch (MVP, MCM, MCPD)
    My blog: http://aboutsqlserver.com

  • Parameterized queries running much slower than ones with hardcoded values

    Very often there is a huge performance difference when using parameters in a query, compared to running the same code after replacing the parameters with hardcoded values: the parameterized version of the code runs much slower!
    The case is not parameter sniffing as it is not a (compiled) stored proc, but code executed directly from the editor and the performance issue has been observed in different versions of SQL Server (2000 and 2005).
    How is this explained and how can the parameterized queries have similar performance with the hardcoded ones?
    Also, why does this happen in some cases and not always?
    Finally, the same is sometimes the case with stored procs: a very slow running proc speeds up tremendously when running its code directly, instead of calling the procedure --and even faster, according to the previous, when its parameters are replaced with
    hardcoded values 

    >>The case is not parameter sniffing as it is not a (compiled) stored proc, but code executed >>>directly
    from the editor ?>>>and the performance issue has been observed in different >>>versions of SQL Server (2000 and 2005).
    Something like below?
    --SQL Server creates 3 execution plan rather only one
    DBCC FREEPROCCACHE
    GO
    SELECT *
    FROM Sales.SalesOrderHeader
    WHERE SalesOrderID = 56000
    GO
    SELECT * FROM
    AdventureWorks.Sales.SalesOrderHeader WHERE
    SalesOrderID = 56001
    GO
    declare @i int
    set @i = 56004
    SELECT *
    FROM Sales.SalesOrderHeader
    WHERE SalesOrderID = @i
    GO
    select  stats.execution_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
    ----This time only (we get parameterization)
    DBCC FREEPROCCACHE
    GO
    EXEC sp_executesql N'SELECT  SUM(LineTotal) AS LineTotal
    FROM Sales.SalesOrderHeader H
    JOIN Sales.SalesOrderDetail D ON D.SalesOrderID = H.SalesOrderID
    WHERE H.SalesOrderID = @SalesOrderID', N'@SalesOrderID INT', 56000
    GO
    EXEC sp_executesql N'SELECT  SUM(LineTotal) AS LineTotal
    FROM Sales.SalesOrderHeader H
    JOIN Sales.SalesOrderDetail D ON D.SalesOrderID = H.SalesOrderID
    WHERE H.SalesOrderID = @SalesOrderID', N'@SalesOrderID INT', 56005
    GO
    select  stats.execution_count AS exec_count, 
    LEFT([sql].[text], 80) 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
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • There is anyway to find the tables name where data is getting inserted currently.

    Hi All,
    I need T-Sql Query to find list of tables in which data is getting loaded currently.
    Thanks Shiven:) If Answer is Helpful, Please Vote

    Hi,
    What About This Query:
    SELECT B.TEXT,A.SESSION_ID,A.STATUS,A.COMMAND,A.CPU_TIME,A.TOTAL_ELAPSED_TIME,A.*,B.*
    FROM SYS.DM_EXEC_REQUESTS A
    CROSS APPLY SYS.DM_EXEC_SQL_TEXT (SQL_HANDLE) B 
    WHERE TEXT NOT LIKE '%SELECT B.TEXT,A.SESSION_ID,A.STATUS,A.COMMAND,A.CPU_TIME,A.TOTAL_ELAPSED_TIME,A.*,B.*%'
    --AND TEXT LIKE '%'
    ORDER BY START_TIME DESC
    Thanks Shiven:) If Answer is Helpful, Please Vote
    The query would return the currently executing query irrespective of insert. But, you are looking for the logging of table. Is my understanding wrong?
    If you are looking for what is running on the server, then you can use the above script. The below is the one am using to get those info:
    SELECT r.session_id ,
    (Select Top 1 CON.client_net_address From sys.dm_exec_connections AS CON
    where CON.session_id = r.session_id) Client_Address,
    OBJECT_NAME(qt.objectid, qt.dbid),
    r.[status] ,
    r.wait_type ,
    r.scheduler_id ,
    SUBSTRING(qt.[text], r.statement_start_offset / 2,
    ( CASE WHEN r.statement_end_offset = -1
    THEN LEN(CONVERT(NVARCHAR(MAX), qt.[text])) * 2
    ELSE r.statement_end_offset
    END - r.statement_start_offset ) / 2) AS [statement_executing] ,
    DB_NAME(qt.[dbid]) AS [DatabaseName] ,
    Object_NAME(qt.objectid) AS [ObjectName] ,
    r.cpu_time ,
    r.total_elapsed_time ,
    r.reads ,
    r.writes ,
    r.logical_reads ,
    r.plan_handle
    FROM sys.dm_exec_requests AS r
    CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS qt
    WHERE r.session_id > 50 and r.session_id <> @@SPID

  • Glitch using dm_exec_query_plan

    I was experimenting with sys.dm_exec_query_plan the other day and ran into a strange glitch. The select from dm_exec_query_plan does not seem to want to be restricted to specific databases. I know this because one of the databases on my server was set to
    single-user mode, and when I ran the following query I was getting an error because of that:
    SELECT
    cp.refcounts
    ,cp.usecounts
    ,cp.objtype
    ,cp.[dbid]
    ,cp.objectid
    ,cp.[text]
    ,qp.query_plan
    FROM sys.dm_exec_cached_plans AS cp
    CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle)
    AS st
    CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle)
    AS qp
    JOIN sys.databases db ON db.database_id = qp.dbid
    AND db.name = 'mydb'
    I would have thought that restricting the results to a particular database (one that isn't in single-user mode) would have caused the error not to occur, but it did not. I fiddled around with a couple of other query formulas and finally found one that worked:
    WITH cteCachedPlans AS
    ( SELECT *
    FROM sys.dm_exec_cached_plans AS cp
    CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle)
    AS st
    JOIN sys.databases AS db
    ON db.database_id = st.dbid
    AND db.name = 'STAX'
    SELECT
    cp.refcounts
    ,cp.usecounts
    ,cp.objtype
    ,cp.[dbid]
    ,cp.objectid
    ,cp.[text]
    ,qp.query_plan
    FROM cteCachedPlans AS cp
    OUTER APPLY sys.dm_exec_query_plan(cp.plan_handle)
    AS qp
    WHERE qp.query_plan IS NULL
    Notice that I am using an "outer apply" here. If I use an "inner apply" the error still occurs, even though the results from the CTE are restricted to a single database that is not in single-user mode. This seems like strange behavior
    to me, has anyone else run into it?
    Thanks,
    Ron Rice
    Ron Rice

    I'm not sure what error message you are getting. I guess that I could test myself, but I'm about to withdraw for the night.
    In any case, the filter is necessarily not applied before the operator that results in an error because of the single-user database. Changing CROSS to OUTER APPLY may change the query plan, but that may be pure coincidence.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Procedure cache question

    Does SQL cache the entire TSQL batch or each individual TFS statement in a batch?  For cache match purposes, does it match on the entire batch or each statement within the batch will attempt to match a previously cached plan?
    When I batch together two TSQL queries in mgmt studio and query the dmvs (dm_exec views/functions), I get two separate rows back where each row has a a different plan_handle, sql_handle, query_hash,query_plan_hash, and text.  The text for each row represents
    a single query statement than the entire batch as the MSDN docs suggest.
    select * from mytable1 where id = 1
    select * from mytable2 where id = 2
    go
    SELECT 
    cp.objtype
    ,qs.plan_handle
    ,qs.SQL_HANDLE
    ,QS.query_hash
    ,QS.query_plan_hash
    ,ST.[TEXT]
    ,cp.usecounts
    ,QS.EXECUTION_COUNT
    ,qs.total_physical_reads
    ,qs.total_logical_reads
    ,P.query_plan
    FROM [SYS].[DM_EXEC_QUERY_STATS] AS [QS] 
    INNER JOIN SYS.dm_exec_cached_plans cp on cp.plan_handle = qs.plan_handle
    CROSS APPLY [SYS].[DM_EXEC_SQL_TEXT]([QS].[SQL_HANDLE]) AS [ST] 
    CROSS APPLY [sys].[dm_exec_query_plan]([qs].[plan_handle]) as [p]
    WHERE [st].[text] like '%mytable1%' or [st].[text] like '%mytable2%'
    ORDER BY 1, [qs].[execution_count] desc;
    go
    The MSDN docs suggest that sql handle from dm_exec_query_stats represent a given TSQL batch of statements.   For caching purposes what constitutes a batch?
    SQL2008

    SQL Server caches the plan for the entire batch, the match when looking for a cache entry is based on a hash that is computed over the entire batch. Note that the hash is computed over the batch text as-is. That is, everything counts: spaces, comments, and
    lowercase and uppercase counts differently.
    But that is not all. If two users submits the same query batch, and the batch includes one or more table references where the schema is not specified, and the users have different default schema, that will result in two cache entries.
    Furthermore, there are a number of SET options that must match for a cache hit. For instance, different settings for ARITHABORT will result in two cache entries.
    As I said, SQL Server initially compiles a plan for the entire batch. However, during execution, recompiles may occur for a number of reasons, and recompilation is on statement level. This causes the part of the plan to be replaced, and as I recall the plan_handle
    remains the same.
    What happens in your case, is something called autoparameterisation. You may note that the query text in the cache has changed, and reads:
    (@1 tinyint)SELECT * FROM [dbo].[mytable2] WHERE [id]=@1
    That is not what you submitted. If you take a query batch where autoparameterisation does not occur, you will still see two entries in the output, because there is always one row per statement, but the sql_handle and plan_handle will be the same. For instance
    try this:
    create table mytable1 (id int NOT NULL)
    create table mytable2 (id int NOT NULL)
    go
    DBCC FREEPROCCACHE
    go
    select * from dbo.mytable1 where id in (SELECT id FROM dbo.mytable2)
    select * from dbo.mytable2 where id in (SELECT id FROM dbo.mytable1)
    go
    SELECT
    cp.objtype
    ,qs.plan_handle
    ,qs.sql_handle
    ,qs.statement_start_offset
    ,qs.statement_end_offset
    ,qs.query_hash
    ,qs.query_plan_hash
    ,st.[text]
    ,cp.usecounts
    ,qs.execution_count
    ,qs.total_physical_reads
    ,qs.total_logical_reads
    ,p.query_plan
    FROM [sys].[dm_exec_query_stats] AS [qs]
    INNER JOIN sys.dm_exec_cached_plans cp on cp.plan_handle = qs.plan_handle
    CROSS APPLY [sys].[dm_exec_sql_text](qs.[sql_handle]) AS st
    CROSS APPLY [sys].[dm_exec_query_plan]([qs].[plan_handle]) as [p]
    WHERE [st].[text] like '%mytable1%' or [st].[text] like '%mytable2%'
    ORDER BY 1, [qs].[execution_count] desc;
    go
    DROP TABLE mytable1, mytable2
    I have added the column statement_start_offset and statement_end_offset, so that you can see the entries are per statement.
    By the way, all the DMVs are spelled in lowercase only, and I recommend that you stick to this. One day, you may need to run your queries on a case-sensitive system, and things like SYS.DM_EXEC_QUERY_STATS will not work for you in this case.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Write a SELECT statement in different ways is not the same thing!!!

    Let's take a look
    use AdventureWorks2012
    go
    dbcc freeproccache
    go
    and now select something
    select * from [HumanResources].[vEmployeeDepartmentHistory]
    go
    so, analyzing 'Compiled Plan'
    SELECT usecounts, cacheobjtype, objtype, text
    FROM Sys.dm_exec_cached_plans
    CROSS APPLY sys.dm_exec_sql_text(plan_handle)
    where cacheobjtype = 'Compiled Plan'
    ORDER BY usecounts DESC;
    GO
    and now let's write some SELECT in "fuzzy case"
    dbcc freeproccache
    go
    select * from [HUMANResources].[vEmployeeDepartmentHistory]
    go
    select * from [HumanRESOURCES].[vEmployeeDepartmentHistory]
    go
    select * from [HumanResources].[VEmployeeDepartmentHistory]
    go
    select * from [HumanResources].[vEmployeeDEPARTMENTHistory]
    go
    select * from [HumanResources].[vEmployeeDepartmentHISTORY]
    go
    SELECT * from [HumanResources].[vEmployeeDepartmentHistory]
    go
    select * FROM [HumanResources].[vEmployeeDepartmentHistory]
    go
    and now let's see compiled plans again
    SELECT usecounts, cacheobjtype, objtype, text
    FROM Sys.dm_exec_cached_plans
    CROSS APPLY sys.dm_exec_sql_text(plan_handle)
    where cacheobjtype = 'Compiled Plan'
    ORDER BY usecounts DESC;
    GO
    So, write a SELECT statement in different ways is not the same thing!!!
    Hope it'll be useful
    P.Ceglie

    Yes.  There is little or no query normalization that happens in front of the query plan cache.  It would be a performance tradeoff to parse and normalize the query before matching it to the cached plans.  The benefit of reducing the number
    of plans in the cache probably wouldn't be worth it. 
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Cost threshold for parallelism

    I ran
    Jonathan Kehayias's query to inspect my plan cache for costs and counts (see below for query).  Some of the costs returned were less than 5.  My server is currently configured with the default settings for MAXDOP and the cost threshold for
    parallelism.  I thought the query was only reporting on queries where parallelization had occurred per the clause "WHERE  n.query('.').exist('//RelOp[@PhysicalOp="Parallelism"]') = 1".  Obviously I do not understand what
    the query is doing, should I expect to see results with a StatementSubTreeCost of less than 5?
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
    WITH XMLNAMESPACES
    (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
    SELECT
    query_plan AS CompleteQueryPlan,
    n.value('(@StatementText)[1]', 'VARCHAR(4000)') AS StatementText,
    n.value('(@StatementOptmLevel)[1]', 'VARCHAR(25)') AS StatementOptimizationLevel,
    n.value('(@StatementSubTreeCost)[1]', 'VARCHAR(128)') AS StatementSubTreeCost,
    n.query('.') AS ParallelSubTreeXML,
    ecp.usecounts,
    ecp.size_in_bytes
    FROM sys.dm_exec_cached_plans AS ecp
    CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS eqp
    CROSS APPLY query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple') AS qn(n)
    WHERE n.query('.').exist('//RelOp[@PhysicalOp="Parallelism"]') = 1

    Looks like it returns the plans where Parallelism has been using... I suggest you reading that Jonathan's blog especially comments . As you know
    SQL Server creates and runs a parallel plan for a query only when the estimated cost to run a serial plan for the same query is higher than the value set in cost
    threshold for parallelism
    That means if the cost of the plan is more than  5 sec  , then a parallel query will be created. So of cause you should see the costs more than 5 sec  in the output.
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Dynamic query plan vs normal query plan

    I have a query with like operator.
    DECLARE @query varchar(52)
    SET @query='A12657'
    IF @query IS NOT NULL
    SET @query='%'+LTRIM(RTRIM(@query))+'%'SELECT eord_type_id FROM izdelek
    WHERE (izd_naziv_ANG like @query OR izd_id like @query)
    OPTION (RECOMPILE)
    Query works 1 ms, 5 ms is for plan recompile. The execution plan is:
    But if I run the same query as dynamic sql:
    DECLARE @query varchar(52), @sql NVARCHAR(4000), @paramList NVARCHAR(500)
    SET @query='A12657'
    SELECT @paramlist = N'@query VARCHAR(52)'
    if @query IS NOT NULL
    SET @query='%'+LTRIM(RTRIM(@query))+'%'
    SET @sql=N'SELECT eord_type_id FROM izdelek
    WHERE (izd_naziv_ANG like @query OR izd_id like @query)
    OPTION (RECOMPILE)'
    EXEC sp_executesql @sql, @paramlist, @query
    The execution plan is different and execution time is much slower - 2877 ms.
    Where is the catch? What should I change that dynamic query would work the same.
    What I also don't understand is key lookup at the end of the plan. Since we have clustered index seek at the beginning of the plan, the optimizer could read additional column(eord_type_id) from this index seek.
    And why it is using merge since it has both columns from WHERE clause (izd_naziv_ang and izd_id) included inside index IX_izdelek. izd_id is in fact clustered key.
    How can i improve this query?
    But I would like to know at most, why dynamic sql is so much slower, since the query is totally the same in both cases and how to achieve that both queries have the similar execution time?

    First of all , why do you use LIKE operator instead of EQUAL (=). I see you are looking for exact value..
    --SQL Server creates 3 execution plan rather only one
    DBCC FREEPROCCACHE
    GO
    SELECT *
    FROM Sales.SalesOrderHeader
    WHERE SalesOrderID = 56000
    GO
    SELECT * FROM
    AdventureWorks.Sales.SalesOrderHeader WHERE
    SalesOrderID = 56001
    GO
    declare @i int
    set @i = 56004
    SELECT *
    FROM Sales.SalesOrderHeader
    WHERE SalesOrderID = @i
    GO
    select  stats.execution_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
    ----This time only (we get parameterization)
    DBCC FREEPROCCACHE
    GO
    EXEC sp_executesql N'SELECT  SUM(LineTotal) AS LineTotal
    FROM Sales.SalesOrderHeader H
    JOIN Sales.SalesOrderDetail D ON D.SalesOrderID = H.SalesOrderID
    WHERE H.SalesOrderID = @SalesOrderID', N'@SalesOrderID INT', 56000
    GO
    EXEC sp_executesql N'SELECT  SUM(LineTotal) AS LineTotal
    FROM Sales.SalesOrderHeader H
    JOIN Sales.SalesOrderDetail D ON D.SalesOrderID = H.SalesOrderID
    WHERE H.SalesOrderID = @SalesOrderID', N'@SalesOrderID INT', 56005
    GO
    select  stats.execution_count AS exec_count, 
    LEFT([sql].[text], 80) 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
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to find open query executed once on SQL server

    Hi Experts ,
    Is there any way to identify that open query executed once on Db server using any DMv's ? we are planning enabale opimized for ad-hoc queries on SQL server ?
    Shivraj Patil.

    Hi,
    You can use below query  to find the plans that have been used only once.
    SELECT text, cp.objtype, cp.size_in_bytes
    FROM sys.dm_exec_cached_plans AS cp
    CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
    WHERE cp.cacheobjtype = N'Compiled Plan'
    AND cp.objtype IN(N'Adhoc', N'Prepared')
    AND cp.usecounts = 1
    ORDER BY cp.size_in_bytes DESC
    OPTION (RECOMPILE);
    additionally you can also refer below articles.
    http://sqlmag.com/database-performance-tuning/sql-server-plan-cache-junk-drawer-your-queries
    Plan cache and optimizing for adhoc workloads
    Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    Praveen Dsa | MCITP - Database Administrator 2008 |
    My Blog | My Page

  • SQL Azure: Query Analyzer VS Web Application - Calling Stored Prcocedure

    I have a stored procedure in SQL Azure.
    Calling this stored procedure normally would take 30 minutes.
    I need to call this Stored procedure multiple times (18 times, with different input)
    Scenario 1: When I call this asynchronously from the Web Application, all 18 calls run concurrently so the whole process take about 30 minutes.
    Scenario 2: When I call this same stored procedure from Microsoft SQL Server Management Studio, (each process in a different TAB) they seem to be running very slowly, it has already taken more than 5 hours.
    Is there a reason for this ?
    Is there any difference in calling multiple stored procedures from different tabs ?
    Is this process running Asynchronously ?
    What is the best was to achieve scenario without going via the front end ?

    Is there a reason for this ?
    --When you are running the query, no matter application or SQL Server, please check sys.dm_exec_requests and check the session status in SQL Server and see if any difference.
    Maybe it is caused by blocking when running in SSMS. We need to dig into it.
    I am not sure how you call the procedure asynchronously  in application, but if they are sent to SQL Server within different connections/sessions, then it should be the same as SSMS.
    Is there any difference in calling multiple stored procedures from different tabs ?
    --No.
    Is this process running Asynchronously ?
    --When you start the procedure in SSMS, it is a synchronize session.
    However, the slowness should not be associated with the synchronization or not.
    Per my understanding, for the asynchronously calling in application, it simply means that application goes to execution other code without for SQL Server.
    This does not affect the real time cost in SQL Server.
    What is the best was to achieve scenario without going via the front end ?
    --We need to understand what cause the issue first. Normally they should be almost the same.
    Right now the procedure caused 30 minutes to complete and it is really too long. I think you'd better make adjustment to the code or logic to tune the performance first.

  • What does it mean when the usecounts of Parse Tree for a view is incrementing when a select query is issued against the view?

    I'm using SQL Server 2008 R2 (10.50.4033) and I'm troubleshooting an issue that a select query against a specific view is taking more than 30 seconds consistently.   The issue just starts happening this week and there is no mass changes in data.  
    The problem only occur if the query is issued from an IIS application but not from SSMS.  One thing I noticed is that sys.dm_exec_cached_plans is returning 2 Parse Tree rows for the view -  one created when the select query is issued
    1st time from the IIS application and another one created when the same select query is issued 1st time from SSMS.   The usecounts of the Parse Tree row for the view (the IIS one) is increasing whenever the select query is issued.  The
    usecounts of the Parse Tree row for the view (the SSMS one) does not increase when the select query is issued again. 
    There seems to be a correlation between the slowness of the query and the increasing of the usecounts of the Parse Tree row for the view.  
    I don't know why there is 2 Parse Tree rows for the view.  There is also 2 Compiled Plan rows for the select query.  
    What does the Parse Tree row mean especially the usecounts column?

    >> The issue just starts happening this week and there is no mass changes in data.  
    There might be a mass changes in the execution plan for several reason without mass changes in data
    If you have the old version and a way to check the old execution plan, and compare to the new one, that this should be your starting point. In most cases you don't have this option and we need to monitor from scratch.
    >> The problem only occur if the query is issued from an IIS application but not from SSMS.
    This mean that we know exactly what is the different and you can compare both execution plan. once you do it, you will find that they are no the same. But this is very common issue and we can know that it is a result of different SETting while connecting
    from different application. SSMS is an external app like any app that you develop in Visual studio but the SSMS dose not use the Dot.Net default options.
    Please check this link, to find the full explanation and solutions:
    http://www.sommarskog.se/query-plan-mysteries.html
    Take a look at sys.dm_exec_sessions for your ASP.Net application and for your SSMS session.
    If you need more specific help, then we need more information and less stories :-)
    We need to see the DDL+DML+Query and both execution plans
    >> What does the Parse Tree row mean
    I am not sure what you mean but the parse tree represents the logical steps necessary to execute the query that has been requested. you can check this tutorial about the execution plan: https://www.simple-talk.com/sql/performance/execution-plan-basics/ or
    this one: http://www.developer.com/db/understanding-a-sql-server-query-execution-plan.html
    >> regarding the usecount column or any other column check this link:
    https://msdn.microsoft.com/en-us/library/ms187404.aspx?f=255&MSPPError=-2147217396.
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

Maybe you are looking for

  • Hide a column in hierarchial alv

    hi, how can we hide a column in hirarchical alv, where factory table is used. i'm using cl_salv_hierarchical_alv. here how can we hide a column.

  • Popup window display issue ???

    I want to have a button the with launch a poup window. I know how to do this put what I do not know how to do is have no site display info in the new pop up window. I have done a normal pop up window but it has the address bar in it and on the top of

  • Lost my YouTube app after downloading iOS 6?

    I looked in the general settings and I don't see anything as to what the problem might be.  Not under restrictions.

  • Registering ODAC Dlls

    Hello everyone! Normally before installing my app I install the ODTwithODAC112030. But I've just recently been able to get a hold of a registered copy of Visual Studio 2010 Ultimate and was exploring the Setup Package. I came across the "Global Assem

  • Load Indictor errors - Has anyone resolve this issues

    I made the modifications suggested, but the database will not open because of the error encountered in the alert log file. When trying to start the 8.0.5 database using 8.1.5 executables and libaries, I get the following error messages in the alter l