Friday, April 19, 2013

Using PSSDiag/SQLDiag Manager to collect data on SQL 2012 Instances

If you are like me and you prefer using the PSSDiag / SQLDiag Manager to create the XML configuration file and run SQLDiag to collect performance data from your SQL Server, then you are probably wondering why there hasn't been an update to include SQL 2012 yet. Never fear there is only a small "hack" you need to do within the produced configuration file for it to run against SQL 2012.

First off use PSSDiag / SQLDiag Manager as you would normally for SQL 2008 R2. Here's a high level of what I configure when I am only looking to collect a Profiler Trace and PerfMon which will typically satisfy the needs of most SQL Engineers unless you are troubleshooting a lower level performance issue.

  1. Select "SQL 2008" as the SQL Version
  2. Enter the machine name
  3. Enter the instance name (if required)
  4. Ensure that Windows Auth is selected
  5. Deselect Event Logs, Shutdown from Machine Wide Diagnostics
  6. Deselect SQLDIAG, and Shutdown from Instance-Specific Diagnostics
  7. Ensure that Trace is checked
  8. Select either the _GeneralPerformance10.xml or DetailedPerformance10.xml template depending on the level of Statement detail you wish to collect.
  9. Within the Custom Diagnostics section deselect the SQL Base, MSInfo, SQL Best Practises, SQL 2008 Perf Stats, SQL Dump
  10. Click the Save button
  11. Enter the path where you wish to save the .cab file.
  12. When prompted select SQL 2008 R2



Now is where you must modify the generated XML so it will work with SQL 2012. Here is what to do:

 
  1. Locate the cab file you generated and extract it
  2. With in the extracted files, locate the PSSDiag.xml and open it in Notepad (or your favourite XML editor)

  3. Locate the node and change the value of ssver to 11.

    The original xml will look like:


    The modified xml should now be:
  4. Save the XML and move it back into the .cab if required.
  5. Copy the files/cab to your server and run it as usual.
Additional Tip......

I will usually also modify the PSSDiag.cmd file to set an end time so that if I schedule the data collection it will stop without user interaction. Also this helps in case some operational issues arise and distract enough to forgot to stop the collection.

To do this add the /E parameter to the end of the call to SQLDiag and supply the duration in the format of +HH:MM. So if I was to set SQLDiag to stop after 2 hours the line would look like:

%diagEXE% /O output /I pssdiag.xml /P %1 %2 %3 %4 %5 %6 %7 %8 %9 /E +02:00



NOTE: I haven't actually gone through and validated if there are any different events we need to start capturing for SQL 2012, but should I find any I will update this post. Also I should point out that SQL Profiler has been marked as a depreciated feature and may be removed from future releases, which makes Extended Events the recommended method of capturing/monitoring SQL activity moving forward.

Legal Stuff: The contents of this blog is provided “as-is”. The information, opinions and views expressed are those of the author and do not necessarily state or reflect those of any other company with affiliation to the products discussed. This includes any URLs or Tools. The author does not accept any responsibility from the use of the information or tools mentioned within this blog, and recommends adequate evaluation against your own requirements to measure suitability.

Sunday, April 14, 2013

Undocumented SQL fun: Using and Interpreting the output of DBCC PAGE

While discussing the undocumented SQL Server DBCC PAGE function with some fellow engineers I discovered that there aren't really any recent posts.

Why is DBCC PAGE useful?

Even with the improvements in technology most performance bottlenecks still occur within the storage layer. For this reason it can be very useful for a SQL Engineer to look into the way that data is actually stored within the database pages. To do this we need a function, and this is what DBCC PAGE offers us.

If you are new to SQL Server's storage structure then you should refer to BOL however the following is an extract from http://msdn.microsoft.com/en-US/library/ms190969(v=sql.105).aspx

The fundamental unit of data storage in SQL Server is the page. The disk space allocated to a data file (.mdf or .ndf) in a database is logically divided into pages numbered contiguously from 0 to n. Disk I/O operations are performed at the page level. That is, SQL Server reads or writes whole data pages.
Extents are a collection of eight physically contiguous pages and are used to efficiently manage the pages. All pages are stored in extents.

As I mentioned DBCC PAGE is an undocumented command, so this does come with no-warranty and won't be supported if you try and call support..... use at your own risk..... so be careful if you start using it on production!


Interpreting DBCC Page Output

The first step before we run DBCC PAGE is that we must find out the Page ID that we are interested in looking at the DMF sys.dm_db_database_page_allocations as this will provide us the information we require. This DMF takes the following parameters.

sys.dm_db_database_page_allocations([DatabaseID], [TableID], [PartitionID], [IndexID], [Mode])

In earlier releases of SQL Server we had to use the DBCC IND([Database], [Table], [Unk],[Unk]) to obtain this information and the Page Id.

For example if we wanted to return all pages from the table dbo.Test then we would use the following query:

SELECT *
FROM sys.dm_db_database_page_allocations(db_id('FragTest'), object_id('dbo.Test'), NULL, NULL, 'DETAILED')

As this is a dynamic management function we can also restrict the results using a typical where clause such as the following which ensures we only see pages stored at the leaf level:

SELECT *
FROM sys.dm_db_database_page_allocations(db_id('FragTest'), object_id('dbo.Test'), NULL, NULL, 'DETAILED')
WHERE page_level = 0


While there are many important columns returned by this data, some of the main columns of interest are the following:

Column Description
database_id The database that the page belongs to. Only really relevant if you do not provide the Database ID to the DMF.
object_id The Object ID that owns the page.
index_id The index ID that the page belongs to (e.g. 0 = heap, 1 = clustered, 2...etc)
partition_id The partition id within the database that this page is created in.
extent_file_id The file ID that this page has been created in.
allocated_page_iam_page_id The Page ID for the IAM managing this page.
allocated_page_page_id The Page ID. We need this when we perform the next steps.
page_type The numerical value that represents the page type. Refer below.
page_type_desc The friendly name for the page type (e.g. DATA_PAGE). Refer below.
page_level Describes the level that page exists at (e.g. 0 = Leaf level or Heap level in non-btree, 1 = Intermediate Level of the index, >=2 Additional Intermediate level or if the highest level then the root node.


Once we have found this information we can start to dig further into the page we wish to view. But how do we identify which page to look at.... I'll cover that in another blog where I will explain the levels etc. For this post lets just take a DATA Page and view that, but how do we do that.

Looking at a cut down column list of the above query:



We can see we have 2 indexes related to the table dbo.Test, a Clustered Index and a Non-Clustered index based on the Index_Id column. So we will pick a DATA_PAGE from each.

Before we can run the DBCC PAGE command we need to enable a traceflag to that the output of the command is returned to the client, otherwise it is only written to the SQL ERRORLOG file.

DBCC TRACEON (3604);

First lets look at page 280 and so we will use the DBCC PAGE function but we need to supply the following params:

DBCC PAGE([Database], [FileID], [Allocated_Page_Page_ID], [View])

The view parameter takes a value from 0 to 3. A value of 0 returns only the Page Header info, a value of 1 or 2 will include the Offset table, and 3 includes all of the details of the slots. Each view offers it's own benefits so playing around with which one suits your purpose or provides you the information is recommended.

For example:

DBCC PAGE('FragTest',1,280, 3)

The output of this command is where it starts to get detailed as it is reported in Text via the Messages tab. In this case we are looking at the Clustered Index (or Heap) but if we were looking at the Non-Clustered index (as we will below) we would also receive a Result set containing the table of key values and their hash values used by SQL Server to traverse through the B-Tree or Heap structures.


NOTE: This is only the Page Header section of the page shown here.


As you can see there is quite a bit of information within the output. To help you identify certain parts of data the following has been provided.


Field Description
m_level Values indicate if the page is located at the Leaf (0), Intermediate (1), or Root level.
m_type(see table blow)
Metadata: ObjectId The object_id of the object which owns the page (e.g. a table's object id)
Metadata: IndexId Value indicates the ID of index (zero = heap, 1 = clustered, >=2 non-clustered)
m_slotCnt Number of slots in use on this page
m_freeCnt Space free within page (devide this by average slot record size's to see how many more slots/rows can be added before a new page is required



The following table outlines the numerical values for the m_type otherwise known as the Page Type and their corresponding Name and Description to provide an easy reference when trying to determine which page you are viewing from the PAGE function output.


Value Name Description
1 DATA_PAGE Holds the records
2 INDEX_PAGE B-tree (Clustered Index) records
8 GAM_PAGE file allocation map page (free extents in a file)
9 SGAM_PAGE small extent file allocation map page (extents supporting single page allocation)
10 IAM_PAGE scanable object allocation map page (extents allocated to a given object)
11 PFS_PAGE space usage on a page by page basis as well as allocation state


As mentioned above the screen shot of the DBCC PAGE output is only the Page Header. If you included the View parameter of 1 or 2 then you would also have the OFFSET TABLE at the end of the output which looks like:


This table is how the Database Engine locates the specific row within the Page as the offset references the Slots within the Page which are also included in the output like the following:



NOTE: The actual output will vary depending on the view mode supply to the PAGE function, or the actual data.


As I mentioned this is the output we receive when looking at the Clustered Index or Heap data, but what about if we look at Non-Clustered data pages. So lets look at page 296 and this time we will use a different view mode param.

DBCC PAGE('FragTest',1,296, 3)

While most output is similar under the Messages tab, we now receive the Results table with a record set describing the Index Key, related key from the Clustered Index (or RID if supported by a Heap table), as well as a Unique Qualifier if we have not specified the index key to be unique because for SQL Server to lock the resource this is required. We are also presented with the Hash key but that is used for resource locking and a whole other discussion.



So that is the basics for interpreting the output of the DBCC PAGE command. Of cause once you have the basics you can really get deep into the structure of your data and it can become much more complex, but I hope this guide at least provides a grounding to allow you become more familiar with the structure.

I will be posting more about interpreting this data along with the B-Tree or Heap structures, and that process will go much deeper into this topic.


Legal Stuff: The contents of this blog is provided “as-is”. The information, opinions and views expressed are those of the author and do not necessarily state or reflect those of any other company with affiliation to the products discussed. This includes any URLs or Tools. The author does not accept any responsibility from the use of the information or tools mentioned within this blog, and recommends adequate evaluation against your own requirements to measure suitability.

Saturday, April 13, 2013

A look into SQL Server's Plan Caching when object names are not fully qualified

The other day while demonstrating the circumstances which control when SQL Server's Optimiser will create a new query plan or reuse a plan from cache I was asked an interesting question. While I hadn't come across the specific scenario before, I presented my logic based on my knowledge of the optimiser's behaviour and that it would be an interesting investigation. In this blog is my investigation and I am pleased to say my initial answer (based on logical thought) was correct.

Scenario
We have 2 Tables in a database with the same name but owned by separate schema's, if a user executes a query against one of those tables but does not fully qualify the table name using the owning schema (i.e. relies on their default schema to qualify the name), and another user who's default schema would qualify to the other table within the database runs an identical query, would the Optimiser use the same plan for both.

My Initial Thoughts
While not having investigated this specific behaviour before, my knowledge of the Optimisers behaviour is that it would try and fully qualify the name while generating the Query Plan and therefore create separate plans regardless of if the object name is fully qualified or not.

The Investigation
To reproduce this behaviour I have created a test database [CacheTest] and within that database 2 schemas, TestSchema1 and TestSchema2, along with this 2 logins, TestUsr1 and TestUsr2 which are mapped to the database and schema's respectively. Also within the database are 2 tables, one for each schema [TestSchema1].[ProcCacheTest] and [TestSchema2].[ProcCacheTest], and each table has been populated with some test data.

Lets start by ensuring we have a nothing in our plan cache so it is easier to witness the behaviour, obviously you don't want to do this on a production system.

DBCC FREEPROCCACHE

Now we need to run a query as each user individually.

Open a New Query Window and change the connection to authenticate as [TestUsr1] and then run:

SELECT * FROM [TestSchema1].[ProcCacheTest]
WHERE SomeDate = '19000107'

Then open a New Query Window and change the connection to authenticate as [TestUsr1] and then run.

SELECT * FROM [TestSchema2].[ProcCacheTest]
WHERE SomeDate = '19000107'

Now check the cache, for that I am going to use the script that I wrote in my blog here. Nothing special in these results as we have specified the Schema name so we get 2 individual Query Plans cached.



So lets find out what happens when we don't specify a Schema name (i.e. we don't Fully Qualify the object name). Run the following from the connection context of [TestUsr1]:

SELECT * FROM [ProcCacheTest]
WHERE SomeDate = '19000107'

So what does the cache tell us.


As you can see a new Query Plan is cached. Again nothing unexpected here as we changed the text being executed (removed the schema name) so the query text no longer matches and we know that even the inclusion of an extra White Space, Line Break or even a change in Character Case would cause this behaviour.

How about if we execute this exact same query under the context of the [TestUsr2], and be sure that it is the exact same query with no extra White Space or variance in text.

SELECT * FROM [ProcCacheTest]
WHERE SomeDate = '19000107'

The results of this query should return data from the [TestSchema2].[ProcCacheTest] table, even though we don't specify the schema because the users default schema will map back to the table.

After executing the query lets check the cache again.


Whoa, we now have a 4th Plan in the cache, but wait the Query Text looks identical yet the optimiser has generated a new plan. But how can we be sure we are looking at two completely different statements? The sys.dm_exec_query_stats DMV can help us there as it includes the Query_Hash column, and this is the binary hash value calculated on the query and used by the Optimiser to identify queries with similar logic.

So lets add that into the result set.



As you can see the Query Hash for the 2 queries are different, but wait the Query Hash for the queries in rows in 1 and 4 are identical, and so is the Hash for queries 2 and 3 which match the pairs of statements we executed under each user context. So this verifies to us that the Optimiser is creating the Query Plan based on the Fully Qualified Object path, not just the text we enter (in fact you can verify this even further by looking at the Query_Plan_Hash as it shows the same paired values).

We can also use the query_plan output of the sys.dm_exec_query_plan DMV to view the xml or graphical plan, and from within the plan we can see that the Predicate has the fully qualified object name.



Wow this is great, but lets just be sure because we know some connection providers will use the Prepare / Execute method or maybe we are using the Forced Parameterisation option. So lets test with the sp_executesql to ensure parameterisation of the SQL text.

I executed the following in the context of [TestUsr1]

exec sp_executesql @stmt = N'SELECT * FROM [ProcCacheTest] WHERE SomeDate = @1'
, @params = N'@1 varchar(8)'
, @1 = '19000107';

And then the following in the context of [TestUsr2]

exec sp_executesql @stmt = N'SELECT * FROM [ProcCacheTest] WHERE SomeDate = @1'
, @params = N'@1 varchar(8)'
, @1 = '22000107';

Note that it was my intention to use a different date, due to the data that I have in my [TestSchema2].[ProcCacheTest] table and we have already proved that it will not perform a direct match.

So we check the cache again.


Again we see the same behaviour, the Optimiser creates a new Query Plan in the cache, but it recognises that the statements relate to each other based on the Fully Qualified Object path (see the Query Hash or Query Plan Hash columns).

So after all this we can see that the Optimiser is working as we expect, and mapping the Query Plans to the individual objects based on qualified object paths regardless of if the user names the objects correctly or not. Of cause the recommendation should always still be to qualify the name of the object with the Schema to reduce this additional work that the optimiser is required to do as well as some of the other issues that it can cause.

Thanks for reading and props to the student in the recent workshop that spiked my curiosity on this subject :)

Legal Stuff: The contents of this blog is provided “as-is”. The information, opinions and views expressed are those of the author and do not necessarily state or reflect those of any other company with affiliation to the products discussed. This includes any URLs or Tools. The author does not accept any responsibility from the use of the information or tools mentioned within this blog, and recommends adequate evaluation against your own requirements to measure suitability.

Friday, April 12, 2013

TSQL to find Cached Plans within SQL Server

The following SQL Statement is based off a number of DMV's and DMF's and allows us to look at the query statistics and cached query plans. This becomes useful when trying to determine how SQL Server is caching the execution query plans for our statements, either Adhoc or Proc, but more on that below.

SELECT qs.last_execution_time
, qs.execution_count
, qs.plan_generation_num
--, qs.plan_handle
--, qs.query_plan_hash
--, qs.query_hash
, cp.refcounts as [QueryPlan_RefCounts]
, cp.usecounts as [QueryPlan_UseCounts]
, cp.size_in_bytes as [QueryPlan_SizeBytes]
, cp.cacheobjtype as [CacheObjType]
, cp.objtype as [ObjType]
--, qs.statement_start_offset
--, qs.statement_end_offset
, st.text as [QueryText]
, SUBSTRING(st.text, qs.statement_start_offset/2,
(CASE WHEN qs.statement_end_offset = -1
THEN LEN (CONVERT (nvarchar(max), st.text)) * 2
ELSE qs.statement_end_offset END -
qs.statement_start_offset)/2) as [StmtText]
, qp.query_plan as [QueryPlan]
FROM sys.dm_exec_query_stats 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 qp
WHERE st.text NOT LIKE N'%sys.dm_%'
AND st.text LIKE N'%'
ORDER BY qs.last_execution_time DESC;

To look for query's related to a specific table or object, then change the where statement as follows:
AND st.text LIKE N'%MyTableName%'


So why would we want to care about the plan cache?

In an environment with lots of adhoc statements a problem can certainly arise where SQL Server does not reuse existing cached plans efficiently. This is because the predicate values are being recorded  along with the plans for adhoc statements within the cache. Say for example you have a query such as:

SELECT *
FROM dbo.ProcCacheTest
WHERE someDate = '19000605'

well this would generate a plan within the cache, but then if the application/user reissues the same statement but using different value such as:

SELECT *
FROM dbo.ProcCacheTest
WHERE someDate = '19000608'

This will result in an entirely new plan being generated and cached for the statement. Of cause if the statement is reissued with the exact same predicate values then it will reuse the existing plan from the cache. However if you have an environment with lots of this type of activity and with a large number of different predicate values in use, then this could cause your plan cache to be consumed by all of these statements and not allow other statements to have their plans cached correctly. In other words cause memory pressure within the plan cache and overall resulting in a degradation of performance.

So how can we avoid this, well if we wrap the adhoc query up into a stored procedure such as:

CREATE PROCEDURE dbo.myProcCacheTest (
@pDate varchar(15)
) 
as
SELECT *
FROM dbo.ProcCacheTest
WHERE someDate = @pDate
GO

now when the stored procedure is executed the SQL Optimiser will create a plan in the cache for the statement but with parameterization (i.e. without tracking the actual values of the search predicate).

We can also use the Optimize For Ad Hoc Workloads advanced system setting to ensure that SQL Server doesn't cache plans for adhoc statements unless they are executed more than once. However as this means the Optimizer will only create Query Plan Stubs in the cache for individual executions and then only create full Query Plans in the cache after a query's execution count is >1 it may not fix your problem as it may simply allow for more space within the Plan Cache to store these single execution queries.

There is also another option which is to use the  FORCE PARAMETERIZATION option on the database, then this will force the Optimizer to convert the search predicate within the adhoc queries to a parameter before generating the plan, thus allowing the plan to be reused. This setting doesn't support all data types so you may still find some adhoc queries being cached. In addition to this be extremely careful about implementing these type of settings in a production environment as while they can provide a vast improvement, in some cases it can have a less desired effect, it all depends on the way the exact queries are being processed.

Still the greatest improvement can be gained from removing the adhoc queries through the use of Stored Procedures and another advantage that a Stored Procedure offers us is that the individual statements with in the procedure are cached with individual plans, and we can see those individual statements/plans using the same statement above. I have commented out the query_hash and query_plan_hash columns, but these are how SQL Server tracks the unique statements and plans within it's cache.

So if we had a stored procedure like:

CREATE PROCEDURE dbo.myProcCacheTest (
@pDate varchar(15)
)asSELECT *
FROM dbo.ProcCacheTest
WHERE someDate = @pDate;

DECLARE @pDate2 DateTime = DateAdd(Day, 7, @pDate);
SELECT *
FROM dbo.ProcCacheTest
WHERE someDate >= @pDate
AND someDate <= @pDate2;
GO

If we were to review the cache for this stored procedure we would find a plan in the cache for the first select query and then another for the second select query. Each will have the same plan_handle, but will have individual query_plan_hash and query_hash values.

Other aspects which are useful to gain from looking at the Cache is when plans are regenerated through Recompile, either due to data modification, SET options, or referenced object schema changes. Remember though that when you change the schema of a procedure it's associated cached plans are dropped and removed.

Enjoy digging deeper into the plan cache.

Legal Stuff: The contents of this blog is provided “as-is”. The information, opinions and views expressed are those of the author and do not necessarily state or reflect those of any other company with affiliation to the products discussed. This includes any URLs or Tools. The author does not accept any responsibility from the use of the information or tools mentioned within this blog, and recommends adequate evaluation against your own requirements to measure suitability.