Posts belonging to Category SQL Server 2005



Webcast Today – Using XML to Query Execution Plans

I’ll be speaking for the SQL PASS Database Administration Virtual Chapter today at 12 PM Eastern time.  The topic will be Using XML to Query Execution Plans.  The abstract for the event is the following:

SQL Server stores its execution plans as XML in dynamic management views. The execution plans are a gold mine of information. From the whether or not the execution plan will rely on parallelism to what columns are requiring a key lookup after a non-clustered index seek. Through a the use of XML this information can be available at your fingertips to help determine the value and impact of an index and guide you in improving the performance of your SQL Server databases. In this session we’ll look at how you can begin to understand and query the structure of the execution plans in the procedure cache. Also, we’ll review how to uncover some potential performance issues that may be lurking in your SQL Server.

You can get to the event here.

Webcast Next Week – Using XML to Query Execution Plans

I’ll be speaking for the SQL PASS Database Administration Virtual Chapter next week.  It’ll be on July 28 at 12 PM Eastern time.  The topic will be Using XML to Query Execution Plans.  The abstract for the event is the following:

SQL Server stores its execution plans as XML in dynamic management views. The execution plans are a gold mine of information. From the whether or not the execution plan will rely on parallelism to what columns are requiring a key lookup after a non-clustered index seek. Through a the use of XML this information can be available at your fingertips to help determine the value and impact of an index and guide you in improving the performance of your SQL Server databases. In this session we’ll look at how you can begin to understand and query the structure of the execution plans in the procedure cache. Also, we’ll review how to uncover some potential performance issues that may be lurking in your SQL Server.

If you register for the event ahead of time you will be entered into a drawing brought to us from CA, our event sponsor.  You can get to the event here.

Webcast Today – Performance Impacts Related to Different Function Types

I’ll be speaking for the SQL PASS Performance Virtual Chapter later today starting at 12 PM Eastern time.  The topic will be Performance Impacts Related to Different Function Types.  The abstract for the event is the following:

User defined functions provide a means to encapsulate business logic in the database tier.  Often the purpose of the encapsulation is to provide standard method access segments of data within the database.  Unfortunately, not all methods of creating user defined functions are equal.  In this session we’ll review the types of user defined functions and investigate the performance impact in selecting the different types

Goals:

  • Identify purposes for creating user defined functions
  • Discuss the types of user-defined functions
  • Demonstrate performance impact in selecting different types of functions

You can get to the event here.

Webcast Next Week – Performance Impacts Related to Different Function Types

I’ll be speaking for the SQL PASS Performance Virtual Chapter next week.  It’ll be on July 6 at 12 PM Eastern time.  The topic will be Performance Impacts Related to Different Function Types.  The abstract for the event is the following:

User defined functions provide a means to encapsulate business logic in the database tier.  Often the purpose of the encapsulation is to provide standard method access segments of data within the database.  Unfortunately, not all methods of creating user defined functions are equal.  In this session we’ll review the types of user defined functions and investigate the performance impact in selecting the different types

Goals:

  • Identify purposes for creating user defined functions
  • Discuss the types of user-defined functions
  • Demonstrate performance impact in selecting different types of functions

You can get to the event here.

Do You Patch SQL Server Regularily?

Lego DeadlockMicrosoft has released a few new Cumulaive Update for SQL Server. There is an update for each of the supported releases of SQL Server:

Cumulative Updates are primarily intended for SQL Server environments where the issues being resovled are being realized. Though if you are using the components updated by the Cumulative Update it would be good to apply the update.

Unless, of course, you’d rather spend the weekend behind an 8-Ball troubleshooting and resolving an issue that the Cumulative Update would have prevented. The 8-Ball might be a black and blue ball by Monday when you explain to your manager that the issue was completely avoidable.

Patch Regularily

If you aren’t aware, Microsoft has an Incremental Servicing Model. This model provides guidance on what you should expect from Microsoft from a support standpoint for issues with their products. As part of the Incremental Servicing Model, Microsoft is committed to releasing Cumulative Updates every 2 months.

All fine and dandy but what does that have to do with you? Or if today still feels like Monday… So what?

The benefit of this model is that it allows us as administrators of SQL Server to develop a plan to regularily download and install the updates. This plan would, of course, include a process to install the updates in the development and test environments. And, also, detail what the steps are for testing and releasing these updates.

But That’s Not All

Just like practicing your database recovery plan. You do practice this, right? Regularily updating your SQL Server environment provides an opportunity to become familiar with this task. This is a critical skill that every DBA should want to have.

If you are well versed in a simple Cumulative Update deployment you have skill and knowledge that will be critical in other situations. When a hotfix needs to be deployed, you will already know your systems well enough to understand the collateral impact of the deployment. If you suddenly inherit a SQL Serve that hasn’t been maintained since an RTM install, you know what level of patching to place on the server and already have a process in place to get the job done.

Regular updates of your SQL Server environment also gives you the opportunity to read the Cumulative Update notes. You will know what wasn’t working and become an expert on problems that may exist in your environment. I’d rather say, “There is a fix to that issue already in progress. It’s in the Test environment already.” Than have to come back and say, “Microsoft fixed that in an update 6 months ago, I’ll see what we need to do to get the update deployed.”

There are likey countless other reasons to take the time to build a process and skillset around regular patching. The long and the short of it is that it is good for you, good for your company, and the responsible thing to do.

Index Those Foreign Keys

Lego DeadlockToday started with some quality time getting to know a deadlock that had occurred. While working through the deadlock, I noticed that there were a number of foreign key relationships that weren’t indexed on the parent side of the relationship.

I am going to skip over the why to index foreign keys and save that for a later point when I have more time to go through it with some really pretty pictures. Today though, I want to share the scripts that I put together to look for these situations and help prevent issues related to them.

Brute Force Indexing

This first script is a brute force attack on this need. If you set the output for text results in SQL Server Management Studio (SSMS) you’ll get a script with all of the indexes you’ll need to cover all of your foreign key relationships.


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON

;WITH cIndexes
AS (
SELECT i.object_id
,i.name
,(SELECT QUOTENAME(ic.column_id,'(')
FROM sys.index_columns ic
WHERE i.object_id = ic.object_id
AND i.index_id = ic.index_id
AND is_included_column = 0
ORDER BY key_ordinal ASC
FOR XML PATH('')) AS indexed_compare
FROM sys.indexes i
), cForeignKeys
AS (
SELECT fk.name AS foreign_key_name
,'PARENT' as foreign_key_type
,fkc.parent_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.parent_object_id = c.object_id AND ifkc.parent_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.parent_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
UNION ALL
SELECT fk.name AS foreign_key_name
,'REFERENCED' as foreign_key_type
,fkc.referenced_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.referenced_object_id = c.object_id AND ifkc.referenced_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.referenced_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
), cRowCount
AS (
SELECT object_id
,SUM(row_count) AS row_count
FROM sys.dm_db_partition_stats ps
WHERE index_id IN (1,0)
GROUP BY object_id
)
SELECT
'--Missing foreign key index for '+fk.foreign_key_name+CHAR(13)+CHAR(10)+'GO'+CHAR(13)+CHAR(10)+
+'CREATE NONCLUSTERED INDEX FKIX_'+OBJECT_NAME(fk.object_id)+'_'+REPLACE(REPLACE(REPLACE(REPLACE(fk.fk_columns,',',''),'[',''),']',''),' ','')
+CHAR(13)+CHAR(10)+
+'ON [dbo].['+OBJECT_NAME(fk.object_id)+'] ('+fk.fk_columns+')'+CHAR(13)+CHAR(10)+
+'GO'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)
FROM cForeignKeys fk
INNER JOIN cRowCount rc ON fk.object_id = rc.object_id
LEFT OUTER JOIN cIndexes i ON fk.object_id = i.object_id AND i.indexed_compare LIKE fk.fk_columns_compare + '%'
WHERE i.name IS NULL
ORDER BY OBJECT_NAME(fk.object_id), fk.fk_columns

Foreign Key Monitoring

This second script accommodates for those situations when you may not want to just index every foreign key that is out there. Maybe there’s a really old table in the database with a foreign key relationship that just doesn’t matter any more. Is it worth indexing along a vector that won’t lead to any performance impact – either negative or positive? Most likely not.

For this script, the results output a list of foreign keys relationships that are not fully indexed. Included in the result script is a column with XML data in it that contains a script for creating an index. You may notice that the format for this is very similar to the schema created when outputtingmmissing Indexes from execution plans.


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

;WITH cIndexes
AS (
SELECT i.object_id
,i.name
,(SELECT QUOTENAME(ic.column_id,'(')
FROM sys.index_columns ic
WHERE i.object_id = ic.object_id
AND i.index_id = ic.index_id
AND is_included_column = 0
ORDER BY key_ordinal ASC
FOR XML PATH('')) AS indexed_compare
FROM sys.indexes i
), cForeignKeys
AS (
SELECT fk.name AS foreign_key_name
,'PARENT' as foreign_key_type
,fkc.parent_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.parent_object_id = c.object_id AND ifkc.parent_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.parent_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
UNION ALL
SELECT fk.name AS foreign_key_name
,'REFERENCED' as foreign_key_type
,fkc.referenced_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.referenced_object_id = c.object_id AND ifkc.referenced_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.referenced_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
), cRowCount
AS (
SELECT object_id
,SUM(row_count) AS row_count
FROM sys.dm_db_partition_stats ps
WHERE index_id IN (1,0)
GROUP BY object_id
)
SELECT
fk.foreign_key_name
,OBJECT_NAME(fk.object_id) AS fk_table_name
,fk.fk_columns
,rc.row_count AS row_count
,CAST('<!--dex  '+CHAR(13)+CHAR(10)+'Missing foreign key index for '+fk.foreign_key_name+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+'USE ['+DB_NAME()+']'<br--> +CHAR(13)+CHAR(10)+'GO'+CHAR(13)+CHAR(10)+
+'CREATE NONCLUSTERED INDEX []'+CHAR(13)+CHAR(10)+
+'ON [dbo].['+OBJECT_NAME(fk.object_id)+'] ('+fk.fk_columns+')'+CHAR(13)+CHAR(10)+
+'GO'+CHAR(13)+CHAR(10)+'--?>' AS xml) foreign_key_index_schema
FROM cForeignKeys fk
INNER JOIN cRowCount rc ON fk.object_id = rc.object_id
LEFT OUTER JOIN cIndexes i ON fk.object_id = i.object_id AND i.indexed_compare LIKE fk.fk_columns_compare + '%'
WHERE i.name IS NULL
ORDER BY OBJECT_NAME(fk.object_id), fk.fk_columns

Closing Up

The DDL schema output in these scripts is very basic. It doesn’t account for potentially important things like partitions and filegroups. Obviously, you’ll need to modify this for your own environment and don’t just run this on production.

I see a lot of potential in these scripts and am planning to include them as part of preparing for releases when I am clients. A good way to dot the i’s and cross the t’s.

Individual results may vary. No Legos were harmed in the writing on this post.

Doing Something About Auto Generated Names

Zombie Apocafest 2009 - Shaun & EdI like my name.  It provides a point of reference to who I am.  If I am at work and someone calls for “Jason Strate”… that’s me.  If I am at home, the same thing can happen and I still know that it’s me.  I know that no matter where I am, my name will be a constant and it means something when it is called.  Hopefully, it doesn’t mean “late to dinner”.

This same principle applies to the tables and the objects related to those tables.  We give that table a name in the development environment, maybe it’s called “ZombieBaconUnicorn”.  We expect that it will be called “ZombieBaconUnicorn”.  Unfortunately, this doesn’t always ring true with other database objects related to tables; such as Primary Keys and Defaults Constraints.

Random Naming

There are multiple ways to create Primary Key and Default Constraints and they don’t all have an implied name.  Take for instance the following script, what would you assume the names of the Primary Key and Default Constraints would be?

CREATE TABLE dbo.RandomPKandDC
(
RandomPKandDCID int IDENTITY(1,1) PRIMARY KEY CLUSTERED
,Column1 datetime DEFAULT(GETDATE())
)

SELECT name FROM sys.objects
WHERE parent_object_id = OBJECT_ID('dbo.RandomPKandDC')

Did you guess the following names?

image

No?!  Run it on you machine, you’ll get your own unique names.

Non-Random Naming

Getting around the random naming is pretty simple.  Below I’ll would you through the steps.

The first change is how you’ll define the PRIMARY KEY on the table with the CREATE TABLE statement.  Instead of adding PRIMARY KEY CLUSTERED on the column definition, add it to the table as a constraint.

CREATE TABLE dbo.NonRandomPKandDC
(
NonRandomPKandDCID int IDENTITY(1,1)
,Column1 datetime
,CONSTRAINT PK_NonRandomPKandDC_RandomPKandDCID PRIMARY KEY CLUSTERED (NonRandomPKandDCID)
)

Next you want to use the ALTER TABLE statement to add the DEFAULT CONSTRAINT.  Instead of making the default part of the column definition in the CREATE TABLE, you want to name the default as a constraint to name it as it is created.

ALTER TABLE dbo.NonRandomPKandDC ADD CONSTRAINT DF_NonRandomPKandDC_Column1
DEFAULT (getdate()) FOR [Column1]

Take a look at the results of the next query:

SELECT name FROM sys.objects
WHERE parent_object_id = OBJECT_ID('dbo.NonRandomPKandDC')

image

On your server and mine the objects will have the same name.  When you deploy objects build from T-SQL like this from development to test to production they will have the same names.

What the!?

Now there isn’t anything wrong with these random names from the perspective of how your database will perform.  But it will hose up things such as database comparisons and investigating errors.

With database comparisons, the issue is pretty obvious.  If the contents of the object are the same but the name is different then it isn’t the exact same object.  Many tools have options for ignoring these names, but there are some that don’t.  Even when the tool has the option to ignore, you will need to rely on the operator of the tool to disable the feature.

Looking now at investigating errors, I am a big fan of errors that can tell me the problem within the database.  Which of the following is easier to understand.  The first with the random name:

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint ‘PK__RandomPKandDC__5D60DB10′. Cannot insert duplicate key in object ‘dbo.RandomPKandDC’.
The statement has been terminated.

Or the second with the stated name:

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint ‘PK_NonRandomPKandDC_RandomPKandDCID’. Cannot insert duplicate key in object ‘dbo.NonRandomPKandDC’.
The statement has been terminated.

Ok, maybe this isn’t the best example of this type of issue, but it does tell me exactly the issue and because I named the object explicitly I know where the problem is and something about the issue before digging into the schema of the table.

Overall, this is about reducing pain points in building and using your databases.  The easier it is to manage them once they are deployed, the more Bejeweled Blitz you can play on Facebook between your projects.

Renaming the Objects

Maybe I’ve sold you on this idea.  If so, you may be thinking “What the heck do you do with all of my existing databases objects?”  That answer is simple… rename them.  Since the names of these objects isn’t tied to how they are defined, you can easily get them renamed with sp_rename.

The following two scripts are what I use to rename PRIMARY KEY CONSTRAINTS and DEFAULT CONSTRAINTS.

This first one will provide sp_rename statements that you can execute to rename all of your PRIMARY KEY CONSTRAINTS:

;WITH PKNames
AS (
SELECT name AS IndexName
,OBJECT_NAME(object_id) AS TableName
,OBJECT_SCHEMA_NAME(object_id) as SchemaName
,(SELECT '' + c.name
FROM sys.index_columns ic
INNER JOIN sys.columns c
ON ic.object_id = c.object_id
AND ic.index_column_id = c.column_id
WHERE ic.object_id = i.object_id
AND ic.index_id = i.index_id
AND ic.is_included_column = 0
ORDER BY ic.key_ordinal
FOR XML PATH('')) AS Columns
FROM sys.indexes i
WHERE i.is_primary_key = 1
)
SELECT 'EXEC sp_rename ''' + QUOTENAME(SchemaName) + '.' + QUOTENAME(IndexName) + ''', ''PK_' + TableName + '_' + Columns + ''''
FROM PKNames
WHERE IndexName <> 'PK_' + TableName + '_' + Columns

The second one will provide sp_rename statements that you can execute to rename all of your DEFAULT CONSTRAINTS:

SELECT 'EXEC sp_rename ''' + QUOTENAME(OBJECT_SCHEMA_NAME(dc.parent_object_id)) + '.'
+ QUOTENAME(dc.name) + ''', ''DF_' + OBJECT_NAME(dc.parent_object_id) + '_' + c.name + ''''
FROM sys.default_constraints dc
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id
WHERE dc.name <> 'DF_' + OBJECT_NAME(dc.parent_object_id) + '_' + c.name

Hopefully these can be helpful for you as well.

Conclusion

In a roundabout way, this post has been about naming conventions.  Make the world a prettier place by having a convention on naming the objects in your database.

Last word… don’t just run out and use this in your production database without doing your own testing and promoting using your own company’s deployment process.  An obvious statement but one that I thought I should point out since I know how tempting this can be.

EDIT 2010/05/27: Modified scripts to account for schema variations.

Connect Item on Import/Export Wizard

I like using raw files in SQL Server Integration Services (SSIS).  They are a quick way to build data repository that will be used else where in a package or for use with a separate package.  In a recent project, raw files were used to move client data around in a new import process that consolidated business logic and improved performance. 

As much as I like raw files, there is a place in SQL Server where the love I have for raw files is lacking.  This is with the Import/Export Wizard in Management Studio.  If you look through the wizard, you’ll find Excel love, Access love, and even some Oracle love.  But there isn’t an option to import or export raw file data.

 

Stop the Madness

Susan Powter said it best, “Stop the Madness”.  Ok, maybe this isn’t madness.  But it sure is irritating when I have to write an SSIS package from scratch to import a raw file to my sandbox database to see what data is in it that is causing issues.  If it were any other data source or destination, there wouldn’t be a need to do that extra work.

Is this extra work very hard?  No, of course not.  But this is a barrier to using this format.  I’ve been pushed away from them before when explaining the need to build a package to view raw file data.  When other formats can be imported with just a few clicks of a button.  The five to ten minutes to stop and build the package and import the data can add up in some situations.  And compating it to the minute or so to use the wizard, this can be a significant time savings when developing and testing SSIS packages.

There is certainly no sense in complaining without trying to fix.  So here it goes…

If you think this idea is kicking, special, or worthy of your support – please go out and vote up the Connect item that has been submitted on it.

Searching for Plans

70999185_58c1ad9d35

A while back I wrote a post on a procedure I created for the DBADiagnostics database that I talk about from time to time.  This procedure allowed users to search the procedure cache to find plans for procedures by database name and object name.  This had worked out pretty good until I noticed something the other day.

The procedure is using the sys.dm_exec_query_stats as the based table for the query to build itself upon.  The trouble with using this DMV is that it doesn’t have all of the plans listed from the procedure cache.  Only those that currently have stats stored for sql_handles.

About the same time I started writing this post, I noticed a post by Adam Machanic (twitter | blog) in which he puts out a warning to those using sys.dm_exec_query_stats.  In that post, he discusses how the ALTER TABLE statement can result in a batch missing this DMV.

Considering all this lends itself to the question, is there a better DMV that can be used to find plans in the procedure cache?

Use sys.dm_exec_cached_plans Instead

Another DMV that has this information in it is the DMV sys.dm_exec_cached_plans.  This DMV is designed to provide a list of all cached plans in the procedure cache.  To illustrate the difference, lets take a look at the following two queries.


SELECT COUNT(DISTINCT plan_handle)
FROM sys.dm_exec_cached_plans
GO 

SELECT COUNT(DISTINCT plan_handle)
FROM sys.dm_exec_query_stats
GO

On my system, the following results are returned:

image

The first value is the number of plan_handles in sys.dm_exec_cached_plans.  The second is the number of plan_handles in sys.dm_exec_query_stats.  There is a substantial difference between the two.  This is something you’d be expecting based on the information at the start of this post.

Query to Find Cached Plans

Now that I’ve outlined the issues with my original post, lets take a look at a script that will query the procedure cache to look for plans stored for stored procedures and other database objects.


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
GO

DECLARE @DatabaseName sysname
    ,@ObjectName sysname 

SELECT @DatabaseName = 'msdb'
    ,@ObjectName = 'sp_jobhistory_row_limiter';

WITH PlanSearch
AS (
      SELECT qp.dbid
            ,qp.objectid
            ,DB_NAME(qp.dbid) as DatabaseName
            ,OBJECT_NAME(qp.objectid, qp.dbid) as ObjectName
            ,cp.usecounts
            ,cp.plan_handle
      FROM sys.dm_exec_cached_plans cp
            CROSS APPLY sys.dm_exec_text_query_plan(cp.plan_handle, DEFAULT, DEFAULT) qp
    WHERE cp.cacheobjtype = 'Compiled Plan'
      AND (DB_NAME(qp.dbid) = @DatabaseName OR NULLIF(@DatabaseName,'') IS NULL)
    AND (OBJECT_NAME(qp.objectid, qp.dbid) = @ObjectName OR NULLIF(@ObjectName, '') IS NULL)
)
,PlansAndStats
AS (
      SELECT ps.DatabaseName
        ,ps.ObjectName
        ,ps.usecounts -- Use in place of qs.execution_count for whole plan count
        ,CAST(SUM(qs.total_worker_time)/(ps.usecounts*1.) as decimal(12,2)) AS avg_cpu_time
        ,CAST(SUM(qs.total_logical_reads + qs.total_logical_writes)/(ps.usecounts*1.) as decimal(12,2)) AS avg_io
        ,SUM(qs.total_elapsed_time)/(ps.usecounts)/1000 as avg_elapsed_time_ms
        ,ps.plan_handle
    FROM PlanSearch ps
            LEFT OUTER JOIN sys.dm_exec_query_stats qs ON ps.plan_handle = qs.plan_handle
    GROUP BY ps.DatabaseName
        ,ps.ObjectName
        ,ps.usecounts
            ,ps.plan_handle
)
SELECT ps.DatabaseName
    ,ps.ObjectName
      ,ps.usecounts
      ,ps.avg_cpu_time
      ,ps.avg_io
      ,ps.avg_elapsed_time_ms
      ,qp.query_plan
      ,ps.plan_handle
FROM PlansAndStats ps
      CROSS APPLY sys.dm_exec_query_plan(ps.plan_handle) qp 

Executing the script above provides the following output:

image

The output includes the name of the object being sought and a link to the plan from the procedure cache.  Included with this is some basic performance information from sys.dm_exec_query_stats that can be useful in determining performance variations between the plans returned.

Procedure to Find Plans

For those that like to take these scripts and build stored procedures for them.  I’ve also included a script below that includes this information.

Chapter Review – MVP Deep Dive Chapter 11

A few weeks back I was asked it I’d be interested in reviewing a chapter in SQL Server MVP Deep Dives.  Of course, since I was already reading the book I thought it’d be a good idea.  My review on Chapter 11 – SQL Server Frequently Asked Questions can be found over at sqlperspectives.  If you like my review, you’ll like the book too.  Check it out!